我正在使用PHP 5.4,想知道我所创建的匿名函数是否具有词法作用域?
例如,如果我有一个控制器方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当Access Factory调用传递的函数时,$this会指向定义它的控制器吗?
匿名函数不使用词法作用域,但是$this
是一个特例,在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;
});
}
$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);
});
编辑:正如Matt所指出的那样,PHP 5.4开始闭包中支持$this
。
$this
。请查看这个简短的视频进行解释。 - Matt Kantor$this
是一个特殊变量,具有特殊含义。 - newacct$this
/self
/parent
(如果在类内定义),除非使用use
显式地绑定额外的变量。请参见此演示。 - Matt Kantor