【问题标题】:How do I bind a closure created inside a static function to an instance如何将在静态函数中创建的闭包绑定到实例
【发布时间】:2014-03-02 12:43:33
【问题描述】:

这似乎不起作用,我不知道为什么? 你可以在非静态方法中创建静态闭包,为什么不反过来呢?

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

【问题讨论】:

  • 嗯,似乎也不适用于bindTo。
  • 来自 bindTo 文档“静态闭包不能有任何绑定对象(参数 newthis 的值应该为 NULL),但是这个函数仍然可以用来改变它们的类范围。” php.net/manual/en/closure.bindto.php ,并且由于 bind 只是 bindTo 的静态,我猜你不能在静态上下文上进行非静态闭包。
  • 这已在 PHP 7 中得到修复。请参阅错误 #64761 和 #68792。

标签: php binding closures


【解决方案1】:

正如我在评论中所说,您似乎无法从来自静态上下文的闭包中更改“$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." 我想你将不得不做这样的事情:

    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();

【讨论】:

    猜你喜欢
    • 2013-05-27
    • 2020-03-10
    • 2013-08-25
    • 1970-01-01
    • 2013-05-15
    • 2013-10-15
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多