Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }

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)

like image 325
Dan Lugg Avatar asked Oct 29 '10 17:10

Dan Lugg


1 Answers

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.

like image 200
rojoca Avatar answered Oct 07 '22 23:10

rojoca