5

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.

7
  • Have you read this stackoverflow.com/questions/1912902/… ? Commented Jun 19, 2017 at 12:06
  • Despite of introducing scope private properties are not visible to any other classes. Commented Jun 19, 2017 at 12:08
  • @ponury-kostek tks for the reference. I read it. But l think my question is different from that thread. Commented Jun 19, 2017 at 12:08
  • Try class abstraction as described here php.net/manual/en/language.oop5.abstract.php Commented Jun 19, 2017 at 12:09
  • 1
    It refers to the scope of a class name resolution, not to the scope of variable access. Commented Jun 19, 2017 at 17:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.