2

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.

DudeOnRock
  • 3,685
  • 3
  • 27
  • 58

2 Answers2

2

You are calling a static property from an instantiated class. Just use the name of the class:

return static::$_test;
Tchoupi
  • 14,560
  • 5
  • 37
  • 71
2

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.

tmuguet
  • 1,165
  • 6
  • 10
  • What is the difference between calling ParentClass::$_test like suggested by Mathieu Imbert and calling self::$_test? – DudeOnRock Feb 07 '13 at 18:05
  • 1
    Technically, none: the result is the same. I guess it's a matter of taste, whether you want to explicitly repeat the class name or not. BTW, edited my answer with a link to the PHP documentation. – tmuguet Feb 07 '13 at 18:08