问题描述
PHP 手册说明
在 PHP 之前,不能从匿名函数中使用 $this
5.4.0
在匿名函数页面.但我发现我可以通过将 $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`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!