In a class, we can access static properties/static methods in this class or parent class through self, and you can access the static properties/static methods in the parent class via parent.
But we don't have a keyword. Accessing the static property of a subclass from a method in the parent class is because the parent class was created before the subclass, so it is not a good choice to logically access the static properties of the subclass from the parent class.
But sometimes we have to do this, so we can do it through the Get_class () method:
Get_class () returns the name of this object,
Get_class (obj) returns the name of the object obj,
Look at the following example:
<?phpclass a{function GetName () {echo get_class (); echo Get_class ($this); }}class b extends a{} $a = new A (); $b = new B (); $a->getname (); $b->getname ();
Results: Aaab
---------------------------------------------------------------
With the subclass object name, in the use of the Eval () method, we can implement access to the subclass static property in the parent class method:
<?phpclass a{function GetName () {$class = Get_class ($this); Eval (' $name = '. $class. ':: $name; '); Echo $name; }}class B extends a{public static $name = ' B ';} Class C extends a{public static $name = ' C ';} $b = new B (), $c = new C (); $b->getname (); $c->getname ();
Results: BC
----------------------------------
If a static method is used in the parent class and cannot use $this, is there no way to do it?
Of course not!
Change Class A to the following
Can be compatible with static method calls
<?phpclass a{static function GetName () {$class = Get_called_class (); Eval (' $name = '. $class. ':: $name; '); Echo $name; }}class B extends a{public static $name = ' B ';} Class C extends a{public static $name = ' C ';} B::getname (); C::getname ();
Results BC
This article is from the "Dark Forest" blog, so be sure to keep this source http://mysens.blog.51cto.com/10014673/1856359
Accessing the static properties of subclasses in the PHP parent class