$this php 调用,php-动态引用$ this应该不起作用,但确实可以

根据有关变量变量的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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值