PHP 手册指出
无法使用$this
来自 PHP 之前的匿名函数
5.4.0
on the 匿名函数页面 http://php.net/manual/en/functions.anonymous.php。但我发现我可以通过分配使其工作$this
到一个变量并将该变量传递给use
函数定义处的语句。
$CI = $this;
$callback = function () use ($CI) {
$CI->public_method();
};
这是一个好的做法吗?
有没有更好的访问方式$this
使用 PHP 5.3 的匿名函数内部?
当您尝试对其调用受保护或私有方法时,它将失败,因为以这种方式使用它会被视为从外部调用。据我所知,在 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"
更重要的是,您将能够在运行时更改 $this 指向的匿名函数(闭包重新绑定):
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"
实际上,匿名函数将具有绑定到()方法 http://php.net/manual/en/closure.bindto.php,其中第一个参数可以用来指定$this指向的内容,第二个参数控制可见度应该是多少。如果省略第二个参数,可见性将就像从“外部”调用一样,例如。只能访问公共属性。还要注意bindTo的工作方式,它不会修改原始函数,它返回一个新的.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)