当它尝试调用受保护或私有的方法时,它会失败,因为使用它的方式称为从外部调用。有没有办法解决这个在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的工作方式,它不修改原始函数,它返回一个新的。