[英]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. 由于我正在调用一个不会被覆盖的父类的函数,因此我觉得应该被允许做上面的事情。
You are calling a static property from an instantiated class. 您正在从实例化的类中调用静态属性。 Just use the name of the class: 只需使用类的名称即可:
return static::$_test;
Use return self::$_test
instead of return static::$_test
. 使用return self::$_test
而不是return static::$_test
。
This insures that you access the field $_test
of the class where returnTest
is defined. 这样可以确保您访问定义了returnTest
的类的字段$_test
returnTest
。
See http://www.php.net/manual/en/language.oop5.late-static-bindings.php for reference. 请参阅http://www.php.net/manual/en/language.oop5.late-static-bindings.php以获取参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.