PHP late static binding scope confusion

From PHP mannual second paragraph, it says that:

static:: introduces its scope.

I tried the following example accordingly:

class Father {
    public function test(){
        echo static::$a;
    }
}

class Son extends Father{
    protected static $a='static forward scope';
    public function test(){
        parent::test();
    }
}

$son = new Son();
$son->test(); // print "static forward scope"

It works as described. However, the following example will raise a fatal error:

class Father {
    public function test(){
        echo static::$a;
    }
}

class Son extends Father{
    private static $a='static forward scope';
    public function test(){
        parent::test();
    }
}

// print "Fatal erro: Cannot access private property Son::$a"
$son = new Son();
$son->test(); 

My main question is how to interpret the word scope here? If static introduces Son 's scope to Father , then why private variables are still invisible to Father ?

Are there two things variable scope and visibility scope? I'm new to PHP sorry if this sounds funny.


There are two things at play here: scope and visibility. Both together decide if you can access the property.

As you found in your first test, late static binding lets $a be available in the scope of the Father class. That simply means the variable (not necessarily its value) is "known" to this class.

Visibility decides whether the variables in scope can be accessed by particular classes and instances. A private property is only visible to the class in which it is defined. In your second example, $a is defined private within Son . Whether or not any other class is aware it exists, it can not be accessed outside of Son .

static makes $a a property which is known to Father , but the property's visibility decides whether or not its value can be accessed.

As a test to further help understand it, try using self instead of static . You'll get back a different error that $a is not a property of Father .

链接地址: http://www.djcxy.com/p/58044.html

上一篇: 方法重写与晚期静态绑定?

下一篇: PHP后期静态绑定范围混淆