这似乎不起作用,我不知道为什么?
你可以在非静态方法中创建静态闭包,为什么不反之呢? @H_403_2@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
你可以在非静态方法中创建静态闭包,为什么不反之呢? @H_403_2@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
正如我在评论中所说,似乎你无法从静态上下文的闭包中更改“$this”.
“Static closures cannot have any bound object (the value of the parameter newthis should be NULL),but this function can nevertheless be used to change their class scope.”
我想你必须做这样的事情: @H_403_2@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(),'RegularClass'); $bfunc(); } } StaticFunctions::doStuff();
原文链接:https://www.f2er.com/php/134242.html“Static closures cannot have any bound object (the value of the parameter newthis should be NULL),but this function can nevertheless be used to change their class scope.”
我想你必须做这样的事情: @H_403_2@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(),'RegularClass'); $bfunc(); } } StaticFunctions::doStuff();