PHP 闭包和隐式全局变量作用域 [英] PHP closures and implicit global variable scope
问题描述
有没有一种方法可以隐式将顶级变量声明为全局变量以在闭包中使用?
Is there a way that one can implicitly declare top-level variables as global for use in closures?
例如,如果使用这样的代码:
For example, if working with code such as this:
$a = 0; //A TOP-LEVEL VARIABLE
Alpha::create('myAlpha')
->bind(DataSingleton::getInstance()
->query('c')
)
->addBeta('myBeta', function($obj){
$obj->bind(DataSingleton::getInstance()
->query('d')
)
->addGamma('myGamma', function($obj){
$obj->bind(DataSingleton::getInstance()
->query('a')
)
->addDelta('myDelta', function($obj){
$obj->bind(DataSingleton::getInstance()
->query('b')
);
});
})
->addGamma('myGamma', function($obj){
$a++; //OUT OF MY SCOPE
$obj->bind(DataSingleton::getInstance()
->query('c')
)
.
.
.
闭包是从这样的方法中调用的:
The closures are called from a method as such:
public function __construct($name, $closure = null){
$this->_name = $name;
is_callable($closure) ? $closure($this) : null;
}
所以总结/TL;DR,有没有一种方法可以在不使用 global
关键字或$GLOBALS
超级全局?
So in summary/TL;DR, is there a way to implicitly declare variables as global for use in closures (or other functions I suppose) without making use of the global
keyword or $GLOBALS
super-global?
我在另一个我经常光顾的论坛 (http://www.vbforums.com/showthread.php?p=3905718#post3905718)
I started this topic at another forum I frequent (http://www.vbforums.com/showthread.php?p=3905718#post3905718)
推荐答案
你必须在闭包定义中声明它们:
You have to declare them in the closure definition:
->addBeta('myBeta', function($obj) use ($a) { // ...
否则您必须使用 global
关键字.对于每个使用 $a
的闭包,你也必须这样做.
Otherwise you must use the global
keyword. You have to do this for every closure that uses $a
too.
这篇关于PHP 闭包和隐式全局变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!