问题描述
PHP手册规定
在匿名功能页面上.但是我发现我可以通过将$this
分配给变量并将该变量传递给函数定义的use
语句来使其工作.
on the anonymous functions page. But I have found I can make it work by assigning $this
to a variable and passing the variable to a use
statement at the function definition.
$CI = $this;
$callback = function () use ($CI) {
$CI->public_method();
};
这是一个好习惯吗?
是否有更好的方法使用PHP 5.3访问匿名函数内的$this
?
Is this a good practice?
Is there a better way to access $this
inside an anonymous function using PHP 5.3?
推荐答案
当您尝试在其上调用受保护的方法或私有方法时,它将失败,因为使用该方法相当于从外部调用.据我所知,没有办法在5.3中解决此问题,但是使用PHP 5.4时,它可以按预期工作,即开即用:
It will fail when you try to call a protected or private method on it, because using it that way counts as calling from the outside. There is no way to work around this in 5.3 as far as I know, but come PHP 5.4, it will work as expected, out of the box:
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指向的内容:
Even more, you will be able to change what $this points to at runtime, for anonymus functions (closure rebinding):
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()方法,其中可以使用第一个参数以指定$ this指向的内容,第二个参数控制可见度级别.如果省略第二个参数,可见性将类似于从外部"调用,例如.只能访问公共属性.还要注意bindTo的工作方式,它不会修改原始函数,它会返回一个新函数.
Effectively, anonymus functions will have a bindTo() method, where the first parameter can be used to specify what $this points to, and the second parameter controls what should the visibility level be. If you omit the second parameter, the visibility will be like calling from the "outside", eg. only public properties can be accessed. Also make note of the way bindTo works, it does not modify the original function, it returns a new one.
这篇关于在PHP 5.4.0之前的匿名函数中使用$ this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!