PHP 闭包和隐式全局变量作用域
有没有一种方法可以隐式将顶级变量声明为全局变量以在闭包中使用?
例如,如果使用这样的代码:
$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')
)
.
.
.
闭包是从这样的方法调用的:
public function __construct($name, $closure = null){
$this->_name = $name;
is_callable($closure) ? $closure($this) : null;
}
所以在总结/TL;DR中,有没有一种方法可以隐式地将变量声明为全局变量以在闭包(或其他函数)中使用我想)没有使用 global
关键字或 $GLOBALS
超级全局?
我在另一个我经常光顾的论坛上开始了这个主题(http://www.vbforums.com/showthread.php?p=3905718#post3905718)
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;
}
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?
I started this topic at another forum I frequent (http://www.vbforums.com/showthread.php?p=3905718#post3905718)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在闭包定义中声明它们:
否则您必须使用
global
关键字。您也必须对每个使用$a
的闭包执行此操作。You have to declare them in the closure definition:
Otherwise you must use the
global
keyword. You have to do this for every closure that uses$a
too.