How to bind a closure created inside a static function to an instance

this doesn't seem to work, and I don't know why? you can create static closures inside non-static methods, why not the other way around?

class RegularClass { private $name = 'REGULAR'; } class StaticFunctions { public static function doStuff() { $func = function () { // this is a static function unfortunately // try to access properties of bound instance echo $this->name; }; $rc = new RegularClass(); $bfunc = Closure::bind($func, $rc, 'RegularClass'); $bfunc(); } } StaticFunctions::doStuff(); // PHP Warning: Cannot bind an instance to a static closure in /home/codexp/test.php on line 19 // PHP Fatal error: Using $this when not in object context in /home/codexp/test.php on line 14 
+7
closures php binding
source share
1 answer

As I said in my comment, it seems that you cannot change "$ this" from a closure that comes from a static context. "Static closures cannot have an associated object (the value of the newthis parameter must be NULL), but this function can, however, be used to change their class." I think you will have to do something like this:

  class RegularClass { private $name = 'REGULAR'; } class Holder{ public function getFunc(){ $func = function () { // this is a static function unfortunately // try to access properties of bound instance echo $this->name; }; return $func; } } class StaticFunctions { public static function doStuff() { $rc = new RegularClass(); $h=new Holder(); $bfunc = Closure::bind($h->getFunc(), $rc, 'RegularClass'); $bfunc(); } } StaticFunctions::doStuff(); 
+6
source share

All Articles