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

时间:2014-02-05 20:49:48

标签: php binding closures

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

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

1 个答案:

答案 0 :(得分:6)

正如我在评论中所说,似乎你无法从静态上下文的闭包中改变“$ 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();