Is there a way to ensure that top-level variables are visible in the scope of a closure, without needing to declare them global in the closure itself?
For example; if I'm working with code using a syntax such as this:
Now of course normally one would need to declare it as global or use the $GLOBALS superglobal. The closures are being called from within a method as such:PHP Code:$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')
)
.
.
.
Providing a jQuery-ish syntax. This is all very simplified for use as an example.PHP Code:public function __construct($name, $closure = null){
$this->_name = $name;
is_callable($closure) ? $closure($this) : null;
}
TL;DR: How can I implicitly declare as global the closure scoped variables.




Reply With Quote