2016-11-02 2 views
0

У меня есть этот код, который я хочу сделать метод абстракции в родителя и ребенка будет определить свойствоPHP ACCESSING ребенка от родителей

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

Aha! это оно! спасибо :) –

Смежные вопросы