为什么后期静态绑定不能与 PHP 5.3 中的变量一起使用?
让我们从一些代码开始:
class Super {
protected static $color;
public static function setColor($color){
self::$color = $color;
}
public static function getColor() {
return self::$color;
}
}
class ChildA extends Super { }
class ChildB extends Super { }
ChildA::setColor('red');
ChildB::setColor('green');
echo ChildA::getColor();
echo ChildB::getColor();
现在,PHP 5.3 中使用 static 关键字的后期静态绑定与静态方法配合得很好,所以我认为它会对静态变量产生同样的魔力。嗯,似乎没有。上面的例子并没有像我最初预期的那样打印出“红色”然后“绿色”,而是打印出“绿色”和“绿色”。为什么它适用于方法却不适用于变量?还有其他方法可以达到我预期的效果吗?
Let's start off with some code:
class Super {
protected static $color;
public static function setColor($color){
self::$color = $color;
}
public static function getColor() {
return self::$color;
}
}
class ChildA extends Super { }
class ChildB extends Super { }
ChildA::setColor('red');
ChildB::setColor('green');
echo ChildA::getColor();
echo ChildB::getColor();
Now, late static binding in PHP 5.3 using the static keyword works great with static methods, so I assumed it would do the same magic on static variables. Well, seems it doesn't. The example above does not print out "red" and then "green" as I first expected, but "green" and "green". Why doesn't this work on variables when it works on methods? Is there any other way to achieve the effect I expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
后期静态绑定仅适用于变量/方法的新定义。因此,在您的示例中,
Super
的$color
属性将始终被修改,而不是ChildA
或ChildB
。要使用后期静态绑定,您需要使用static
关键字而不是self
。此外,您需要重新定义ChildA
和ChildB
类的$color
属性:Late static binding will only work for new definitions of variables / methods. Thus, in your example, the
$color
property ofSuper
will always be modified instead ofChildA
orChildB
. To make use of late static binding, you need to use thestatic
keyword instead ofself
. Furthermore, you need to redefine the$color
property of yourChildA
andChildB
classes: