php – 如何将静态函数内创建的闭包绑定到实例

前端之家收集整理的这篇文章主要介绍了php – 如何将静态函数内创建的闭包绑定到实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这似乎不起作用,我不知道为什么?
你可以在非静态方法中创建静态闭包,为什么不反之呢? @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

猜你在找的PHP相关文章