从父节点访问子节点'


PHP Accessing Child's protected value from parent

我有这段代码,我想做的方法抽象在父和子将定义属性

class SuperClass{
    static protected $message = "This is the parent";
    public static function showMessage(){
        echo self::$message."<br/>";
    }
}
class SubClass1 extends SuperClass {
    static protected $message = "This is the first child";
}
class SubClass2 extends SuperClass {
    static protected $message = "This is the second child";
}
SuperClass::showMessage();
SubClass1::showMessage();
SubClass2::showMessage();

我希望看到

This is the parent
This is the first child
This is the second child

但我得到的是

This is the parent
This is the parent
This is the parent

这是一个非常经典的后期静态绑定用例。只需将父类中的关键字"self"替换为"static"

class SuperClass{
    static protected $message = "This is the parent";
    public static function showMessage(){
        echo static::$message."<br/>";
    }
}