PHP closures and implicit global variable scope

2019-02-12 17:21发布

问题:

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:

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.