开发者

How to create a PHP function only visible within a file?

How to create a开发者_如何学JAVA PHP function only visible within a file? Not visible to external file. In other word, something equivalent to static function in C


There is no way to actually make a function only visible within a file. But, you can do similar things.

For instance, create a lambda function, assign it to a variable, and unset it when your done:

$func = function(){ return "yay" };

$value = $func();

unset($func);

This is provided that your script is procedural.

You can also play around with namespaces.


Your best bet is to create a class, and make the method private


Create a class and make the method private.

<?php
class Foo
{
    private $bar = 'baz';

    public function doSomething()
    {
        return $this->bar = $this->doSomethingPrivate();
    }

    private function doSomethingPrivate()
    {
        return 'blah';
    }
}
?>


Use namespace, for apply your own visibility.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜