我正在使用PHP 5.4,想知道我正在制作的匿名函数是否具有词法作用域?
。如果我有一个控制器方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当访问工厂调用传递给它的函数时,$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;
});
}
5.3。x,您可以使用以下解决方案访问$this
:
protected function _pre() {
$controller = $this;
$this->require = new Access_Factory(function($url) use ($controller) {
$controller->redirect($url);
});
}
简而言之,没有,但是您可以访问public方法&函数:
$that = $this;
$this->require = new Access_Factory(function($url) use ($that) {
$that->redirect($url);
});
edit:正如Matt正确指出的,从PHP 5.4开始在闭包中支持$this