根据有关变量变量的PHP文档:
$ this是一个特殊变量,不能动态引用
但是,这似乎是错误的,至少在我测试过的PHP版本上(5.5.12)。
class ThisIsBugged
{
public function __construct()
{
${'this'}->doSomething(); // This works, while it shouldn't
}
}
问题1:如何运作? 根据文档,它不应该。
但是还有更多。
class ThisIsBugged
{
public function __construct()
{
// This does not work, but it could. See below.
${'th' . 'is'}->doSomething();
}
}
它按预期停止执行:
PHP注意:未定义的变量:this
PHP致命错误:调用成员函数doSomething() 非对象。
请注意,已对语句$this进行了评估:“未定义的变量:此”。
但是(这是最奇怪的事情),显式引用特殊变量$this,可以修复方法中在此之前或之后使用的所有动态引用。
class ThisIsBugged
{
public function __construct()
{
// Now it works while it shouldn't
${'th' . 'is'}->doSomething();
// This fixes both the previous and the subsequent calls
$unused = $this;
// Now it works while it shouldn't
${'th' . 'is'}->doSomething();
}
}
问题2:如何明确引用$this才能将所有其他动态引用固定为整个方法中存在的$this?