PHP 静态属性、继承和 self 关键字 [英] PHP Static Properties, Inheritance, and the self keyword
问题描述
这对我来说没有意义:
class A {
public static $value = "a";
public static function get_value(){
return self::$value;
}
}
echo A::$value; // a, this makes sense
echo A::get_value(); // a, this makes sense
class B extends A {
public static $value = "b";
}
echo B::$value; // b, this makes sense
echo B::get_value(); // a? :(
为什么self
指针没有按预期工作,类似于this
?是否有其他关键字可用于实现此目的?
Why doesn't the self
pointer work as expected, similar to this
? Is there another keyword that could be used to accomplish this?
如果我将静态函数添加到 B 类,它现在可以按预期工作.
If I add the static function to class B, it now works as expected.
class B extends A {
public static $value = "b";
public static function get_value(){
return self::$value;
}
}
echo B::get_value(); // b :)
如果该方法包含超过 1 行,则复制+粘贴此功能并在 2 个位置对其进行管理是没有意义的...
If the method contained more than 1 line, it wouldn't make sense to copy+paste this functionality and manage it in 2 locations...
推荐答案
后期静态绑定:
http://php.net/manual/en/language.oop5.late-static-bindings.php
后期静态绑定通过存储在最后一个非转发调用"中命名的类来工作.
late static bindings work by storing the class named in the last "non-forwarding call".
在您的示例中尝试使用 static::
关键字而不是 self::
.
try using static::
keyword instead of self::
in your example.
这篇关于PHP 静态属性、继承和 self 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!