PHP - 静态局部变量

tha*_*guy 6 php static

所以我最近遇到了像这样的代码段:

private static function FOO() {
        static $c = null;
        if ($c == null) {
            $c = new ParentClass_InnerClass();
        }
        return $c;
    }
Run Code Online (Sandbox Code Playgroud)

那么这段代码怎么了?这有什么不同于:

private static $C;

//other methods and fields    

private static function FOO() {
    if(!$self::c) {
        $self::c = new ParentClass_InnerClass();
    }
    return $self::c;
}
Run Code Online (Sandbox Code Playgroud)

或者他们甚至是同一个概念?

Eli*_*gem 7

它们本质上是相同的概念,但范围不同:

class Foobar
{
    private static $c = null;
    public static function FOO()
    {
        if (self::$c === null)
        {
            self::$c = new stdClass;
        }
        return self::$c;
    }
    public static function checkC()
    {
        if (self::$c === null)
        {
            return false;
        }
        return self::$c;
    }
}

Foobar::checkC();//returns false, as $c is null
//function checkC has access to $c
$returned = Foobar::FOO();//returns object
if ($returned === Foobar::checkC())
{//will be true, both reference the same variable
    echo 'The same';
}
Run Code Online (Sandbox Code Playgroud)

然而,如果我们要将代码更改为:

class Foobar
{
    public static function FOO()
    {
        static $c = null;
        if ($c === null)
        {
            $c = new stdClass;
        }
        return $c;
    }
    public static function checkC()
    {
        if ($c === null)
        {
            return false;
        }
        return $c;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用时我们会收到通知checkC:undefined变量.静态变量$ c只能在FOO范围内访问.私人财产在整个班级范围内.真的是这样的.
但实际上,请帮自己一个忙:如果你需要它们,只使用静态(它们也在实例之间共享).在PHP中,你真的需要一个静态的非常罕见.


Ben*_*min 6

它们是相同的概念,除了在第一个代码块中,静态变量是函数的本地变量,并且这样的静态变量可以在任何函数中使用,甚至在类的上下文之外:

function test() {
    static $counter = 0;
    return $counter++;
}

echo test(); // 0
echo test(); // 1
Run Code Online (Sandbox Code Playgroud)