How to access a variable in a parent class using the parent method ::

I have a Protected Variable UserId in Parent Class.i I'm going to extend this variable in my child class, as shown below.

class Main { protected $UserId = "151"; protected static $UserName = "Madhavan"; protected function SampleMethod() { print "This is Sample Method"; } } class SubMain extends Main { function __construct() { print parent::SampleMethod(); print "User Id is ".$this->UserId."<br/>"; print parent::$UserName; print "User Id is ".parent::$UserId."<br/>"; } } 

When I use $ this-> UserId . His seal is beautiful. But when I use Parent :: $ UserId, it shows an error

Fatal error: access to undeclared static property: Main :: $ UserName

Why does it not show for the function that I received through parent :: SampleMethod () , since the function is not static.

+4
source share
4 answers

This is because functions are redefined (therefore, older versions with the same name coexist), and properties are not (declarations simply overwrite each other, and properties should not be re-declared in descendant classes). You always access the ONLY instance only with $this-> if it is not static, and self:: if it is static. (If a property has been declared in several ancestor classes, only one data field remains, so you cannot refer to “others” or “previous”.)

+1
source

The scope resolution operator :: sometimes behaves in an unobvious way. When applied to constants or variables, it is always resolved in a static way.

However, when applied to functions, the execution context of the called user depends on the execution context of the caller's code; the context does not change.

For example, this works great without any warnings:

 class Test { private $a = 123; public function __construct() { Test::test(); self::test(); } public function test() { echo $this->a; } } new Test(); 

The call to self::test() and Test::test() is performed non-statically because __construct() is called non-statically and you are referring to the same class.

To reference any instance variable, for example $a in the above example, you need to use $this-> .

+3
source

If E_STRICT is not activated, you will not get an error, otherwise you will get something like this:

Strict standards: the non-static method parent :: SampleMethod () should not be called statically in ...

0
source

Instead of using a parent, you can access it with the self::$UserName attribute (where it was defined) with the self keyword. If you want to reach your value in a child class (because you override it), it is available through final::$UserName (called late static binding)

0
source

All Articles