PHP closures and implicit global variable scope

2019-02-12 17:11发布

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)

1条回答
神经病院院长
2楼-- · 2019-02-12 17:18

You have to declare them in the closure definition:

->addBeta('myBeta', function($obj) use ($a) { // ...

Otherwise you must use the global keyword. You have to do this for every closure that uses $a too.

查看更多
登录 后发表回答