PHP闭包和隐式全局变量作用域 [英] PHP closures and implicit global variable scope

查看:420
本文介绍了PHP闭包和隐式全局变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以隐式将顶层变量声明为全局变量以用于闭包中?

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,有办法在不使用全局关键字或 $ GLOBALS super-global?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆