Hans Yulian Hans Yulian - 1 month ago 9
PHP Question

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

Answer

This is a very classical use-case of late static binding. Simply replace keyword "self" in the parent class by "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+