php 函数 $this_php – 在匿名函数中使用$this

当它尝试调用受保护或私有的方法时,它会失败,因为使用它的方式称为从外部调用。有没有办法解决这个在5.3,据我所知,但来了PHP 5.4,它会按预期工作,开箱即用:

class Hello {

private $message = "Hello world\n";

public function createClosure() {

return function() {

echo $this->message;

};

}

}

$hello = new Hello();

$helloPrinter = $hello->createClosure();

$helloPrinter(); // outputs "Hello world"

更重要的是,你可以在运行时改变$指向的值,对于匿名函数(闭包重绑定):

class Hello {

private $message = "Hello world\n";

public function createClosure() {

return function() {

echo $this->message;

};

}

}

class Bye {

private $message = "Bye world\n";

}

$hello = new Hello();

$helloPrinter = $hello->createClosure();

$bye = new Bye();

$byePrinter = $helloPrinter->bindTo($bye, $bye);

$byePrinter(); // outputs "Bye world"

有效地,匿名函数将具有bindTo() method,其中第一个参数可以用于指定$ this指向的内容,第二个参数控制可见性级别应该是什么。如果省略第二个参数,可见性将像从“外部”调用,例如。只能访问公共属性。还要注意bindTo的工作方式,它不修改原始函数,它返回一个新的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值