2016-11-02 108 views
0

我有这样的代码,我想要做的方法抽象的家长和孩子将定义属性PHP访问儿童的保护价值

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

这是一个非常经典的使用案例late static binding。 仅仅通过“静态”更换关键词“自我”在父类

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

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

这将为PHP 5.3+

+0

啊哈工作!就是这个!谢谢 :) –