Cha*_*les 7 php closures lexical
我正在使用PHP 5.4,并想知道我正在制作的匿名函数是否有词法范围?
即如果我有一个控制器方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
Run Code Online (Sandbox Code Playgroud)
当Access Factory调用它传递的函数时,$ this会引用它定义的Controller吗?
匿名函数不使用词法作用域,但是$this是一种特殊情况,并且自5.4.0版本起,将自动在函数内部使用.您的代码应该按预期工作,但它不能移植到较旧的PHP版本.
下面将不工作:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) {
echo $methodScopeVariable;
});
}
Run Code Online (Sandbox Code Playgroud)
相反,如果要将变量注入闭包的范围,可以使用use关键字.以下将有效:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) use ($methodScopeVariable) {
echo $methodScopeVariable;
});
}
Run Code Online (Sandbox Code Playgroud)
在5.3.x中,您可以$this通过以下解决方法获得访问权限:
protected function _pre() {
$controller = $this;
$this->require = new Access_Factory(function($url) use ($controller) {
$controller->redirect($url);
});
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅此问题及其答案.