PHP static binding confusion uncertainty

From the PHP mannual second paragraph it says that:

static :: enters scope.

I tried the following example:

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 result in 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 the Son region into Father , then why are private variables still invisible to Father ?

Are there two variable regions and a visibility region? I'm new to PHP, sorry if that sounds funny.

+5
source share
1 answer

There are two things here: scale and visibility. Both will decide together whether you can access the property.

As you discovered in your first test, late static binding allows $a be available in the scope of the Father class. It just means that the variable (not necessarily its value) is โ€œknownโ€ to this class.

Visibility determines whether variables in a scope can be accessed by specific classes and instances. Private property is visible only to the class in which it is defined. In the second example, $a is defined as private inside Son . Regardless of whether he knows any other class, he cannot be accessed outside of Son .

static does $a property, which is known as Father , but the visibility of the property decides whether its value can be accessed.

As a test, to help understand it, try using self instead of static . You will get another error, which $a not a Father property.

+1
source

Source: https://habr.com/ru/post/1268983/


All Articles