PHP从父级访问Child的受保护值

时间:2016-11-02 04:15:00

标签: php oop

我有这个代码,我想在父和子进行方法抽象,将定义属性

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

1 个答案:

答案 0 :(得分:1)

这是late static binding的一个非常经典的用例。 只需用“static”

替换父类中的关键字“self”即可
class SuperClass{
    static protected $message = "This is the parent";

    public static function showMessage(){
        echo static::$message."<br/>";
    }
}

这适用于php 5.3 +