简体   繁体   English

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

[英]PHP Accessing Child's protected value from parent

I have this code that i want to do method abstraction in parent and child will define the property 我有这段代码,我想在父级和子级中进行方法抽象,以定义属性

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();

I would expect to see 我希望看到

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

But what i got is 但是我得到的是

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

This is a very classical use-case of late static binding . 这是后期静态绑定的非常经典的用例。 Simply replace keyword "self" in the parent class by "static" 只需将父类中的关键字“ self”替换为“ static”

class SuperClass{
    static protected $message = "This is the parent";

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

This will work for php 5.3+ 这将适用于PHP 5.3+

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

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