PHP在匿名函数/闭包中是否具有词法范围?

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吗?

Mat*_*tor 7

匿名函数不使用词法作用域,但是$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)

有关详细信息,请参阅此问题及其答案.

  • @newacct:在PHP中,函数不是词法[scoped](http://php.net/manual/en/language.variables.scope.php),至少不符合我熟悉的那个术语的定义.他们从周边范围"封锁",只能访问或影响变量本身里面,(超)全局和`$ this` /`self` /`parent`(如果一个类中定义),除非额外变量明确地与`use`绑定.见[本演示](http://phpfiddle.org/lite/code/5518331). (2认同)