我使用PHP 5.4并想知道我所做的匿名函数是否具有词法作用域?PHP在匿名函数/闭包中有词法范围吗?
即如果我有一个控制器的方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当访问工厂调用它传递的功能,将这一参考控制器的$它被定义?
我使用PHP 5.4并想知道我所做的匿名函数是否具有词法作用域?PHP在匿名函数/闭包中有词法范围吗?
即如果我有一个控制器的方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当访问工厂调用它传递的功能,将这一参考控制器的$它被定义?
匿名函数不使用词法作用域,但是使用$this
is a special case and will automatically be available inside the function as of 5.4.0。您的代码应该按预期工作,但不能移植到较旧的PHP版本。
下面将不工作:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) {
echo $methodScopeVariable;
});
}
相反,如果要注入的变量进入封闭的范围内,可以使用use
关键字。下面将工作:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) use ($methodScopeVariable) {
echo $methodScopeVariable;
});
}
在5.3.x,则应你可以用以下解决方法访问$this
:
protected function _pre() {
$controller = $this;
$this->require = new Access_Factory(function($url) use ($controller) {
$controller->redirect($url);
});
}
总之,没有,但你可以通过它访问公共方法&功能:
$that = $this;
$this->require = new Access_Factory(function($url) use ($that) {
$that->redirect($url);
});
编辑:马特正确地指出support for $this
in closures started with PHP 5.4
啊,好知道它的不同在PHP5.4中(仍然还没有达到我的Debian Stable软件包...可能需要手动安装)。 – Wrikken 2013-05-03 17:32:29
我需要“使用($ this)”吗?还是5.4会自动让您访问$ this? – Charles 2013-05-03 17:42:07
5.4.0+自动绑定'$ this'。看看[这个短片](http://youtu.be/-Ph7X6Y6n6g)解释它。 – 2013-05-03 17:43:48