PHP在匿名函数/闭包中是否具有词法作用域?
我正在使用PHP5.4,想知道我正在制作的匿名函数是否具有词法范围 即,如果我有控制器方法:PHP在匿名函数/闭包中是否具有词法作用域?,php,closures,lexical,Php,Closures,Lexical,我正在使用PHP5.4,想知道我正在制作的匿名函数是否具有词法范围 即,如果我有控制器方法: protected function _pre() { $this->require = new Access_Factory(function($url) { $this->redirect($url); }); } 当访问工厂调用它传递的函数时,$this是否会引用定义它的控制器?匿名函数不使用词法作用域,而是使用。您的代码应该按预期工作,但它不能移植到
protected function _pre() {
$this->require = new Access_Factory(function($url) {
$this->redirect($url);
});
}
当访问工厂调用它传递的函数时,$this是否会引用定义它的控制器?匿名函数不使用词法作用域,而是使用。您的代码应该按预期工作,但它不能移植到旧的PHP版本
以下操作将不起作用:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) {
echo $methodScopeVariable;
});
}
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) use ($methodScopeVariable) {
echo $methodScopeVariable;
});
}
相反,如果要将变量注入闭包的作用域,可以使用use
关键字。以下将起作用:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) {
echo $methodScopeVariable;
});
}
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);
});
}
有关更多详细信息,请参阅。简而言之,否,但您可以通过传递它来访问公共方法和函数:
$that = $this;
$this->require = new Access_Factory(function($url) use ($that) {
$that->redirect($url);
});
编辑:正如Matt正确指出的那样啊,很高兴知道它在PHP5.4中有所不同(它还没有达到我的Debian稳定软件包……可能需要手动安装)。我需要“使用($this)”还是5.4自动给你访问$this的权限?5.4.0+自动绑定
$this
。看看解释。当然,它使用词汇范围。现在常用的每个编程都使用词法范围$this
是一个特殊的变量,具有特殊的含义。@newacct:在PHP中,函数不是词汇性的,至少不是根据我熟悉的术语定义。它们与周围的作用域“隔离”,只能访问或影响自身内部的变量,(超级)全局变量和$this
/self
/父级
(如果在类中定义),除非额外变量与use
明确绑定。看见