繁体   English   中英

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

[英]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/>";
    }
}

这将适用于PHP 5.3+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM