php lazy static binding

After PHP5.3, delayed static binding static was introduced. What problem does it solve? A long-standing problem with PHP's inheritance model is that it is difficult to reference the final state of an extended class in a parent class. Let's look at an example.

The difference between static and self:
self is a pointer within a class, pointing to the static method and attribute
static of this class, so that the parent class can access the overloaded static method of the subclass

 

<?php
class A
{
    public static function echoClass(){
        echo __CLASS__;
    }
    public static function test(){
        self ::echoClass(); echo '<br/>'; // output A 
        static ::echoClass(); // output C 
    }
}
class B extends A
{

    public static function echoClass()
    {
        echo __CLASS__;
    }
}
class C extends A
{

    public static function echoClass()
    {
        echo __CLASS__;
    }
}
C::test(); 

illustrate:

(1) Use the keyword static to indicate which class is called, and it represents that class.

(2) static::method name(): using the static keyword, the method is first searched in the subclass; if it is not found, it is searched in the parent class

in the above code

 self::echoClass(); == A::echoClass(); //So output A

 static::echoClass(); == C::echoClass(); //So output C

effect:

It is difficult to refer to the final state of the extended class in the parent class, which can be solved with static

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325261935&siteId=291194637