Search code examples
phplate-static-binding

Prevent late static binding with static variable access from parent function


Given the following class hierarchy:

class ParentClass {
    private static $_test;

    public function returnTest() {
        return static::$_test;
    }
}
class ChildClass extends ParentClass {
    // intentionally left blank
}
$child = new ChildClass();
echo $child->returnTest();

The output generated is the following error message:
Fatal error: Cannot access property ChildClass::$_test
Is there a way to prevent late static binding from happening? Since I am calling a function of a parent class that is not overwritten, I feel like I should be allowed to do something like the above.


Solution

  • Use return self::$_test instead of return static::$_test.

    This insures that you access the field $_test of the class where returnTest is defined.

    See http://www.php.net/manual/en/language.oop5.late-static-bindings.php for reference.