我正在使用PHP 5.4并想知道我正在制作的匿名函数是否有词法范围?
即。如果我有一个控制器方法:
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当Access Factory调用它传递的函数时,$ this会引用它定义的Controller吗?
答案 0 :(得分:6)
匿名函数不使用词法作用域,而是使用$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);
});
}
有关详细信息,请参阅this question and its answers。
答案 1 :(得分:1)
简而言之,不,但您可以访问 public 方法&传递它的功能:
$that = $this;
$this->require = new Access_Factory(function($url) use ($that) {
$that->redirect($url);
});
Matt正确地指出了support for $this
in closures started with PHP 5.4 ,编辑