PHP object-oriented delayed static binding

php5.3 has begun to support delayed static binding.

Delayed static binding refers to obtaining the final state of the subclass in the parent class. In the parent class, if the self keyword appears, after being inherited by the child class, the self value is still the parent class instead of the child class.

If the self keyword appears in the parent class, and the subclass inherits this code containing self, then you need to consider static deferred binding. Use static instead of self in the parent class.

After all, what does self mean? Self is used in a class to refer to its own static member variable, which means the class name, which can be replaced by the class name. After being inherited by subclasses, self still represents the name of the parent class, not the subclass self.

Demo
Delayed static binding is not used
class Par
{
    
    
    public static function test()
    {
    
    
        echo 'par~~~<br>';
    }

    public static function who()
    {
    
    
        self::test();//self当前类的test方法
    }
}

class Son extends Par
{
    
    
    public static function test()
    {
    
    
        echo 'son~~~<br>';
    }
}

Par::who();//par~~~ 父类的who
Son::who();//par~~~ 父类的who
Use delayed static binding
<?php

/**
 * 延迟静态绑定
 * Class Par
 */

class Par
{
    
    
    public static function test()
    {
    
    
        echo 'par~~~<br>';
    }

    public static function who()
    {
    
    
        static::test();//使用延迟静态绑定
    }
}

class Son extends Par
{
    
    
    public static function test()
    {
    
    
        echo 'son~~~<br>';
    }
}

Par::who();//par~~~ 父类的who
Son::who();//son~~~ 子类的who
to sum up

static delay is the use of delayed static binding static keyword refers to who calls on behalf of who
self on behalf of refers to the object to which the method belongs

Guess you like

Origin blog.csdn.net/qq_41526316/article/details/108501795