Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP late static binding scope confusion

Tags:

php

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.

like image 588
spacegoing Avatar asked Nov 07 '22 20:11

spacegoing


1 Answers

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.

like image 87
Matt S Avatar answered Nov 14 '22 21:11

Matt S