Skip to content

Instantly share code, notes, and snippets.

@lastguest
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lastguest/9509403 to your computer and use it in GitHub Desktop.
Save lastguest/9509403 to your computer and use it in GitHub Desktop.
Javascript like scope heritage
<?php
function foobarbaz(){
// Extract environment object to local scope (not mandatory, you can access the parent scope via $this. Ex. $this->foo )
extract((array)$this);
var_dump($foo, $bar, $baz);
}
// Use reflection for accessing the binded closure to the function.
function call_closure($closurename,$vars){
return call_user_func((new ReflectionFunction($closurename))->getClosure()->bindTo((object)$vars));
}
// The main scope (not global)
function main(){
$foo = [1,2,3,4,5];
$bar = 123456;
$baz = 'Hello!';
// bind the foobarbaz closure to the local scope and call the function
call_closure('foobarbaz',get_defined_vars());
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment