将对象实例绑定到静态闭包

时间:2013-05-31 17:51:25

标签: php binding static closures instance

是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包?

这就是我的意思......

<?php
class TestClass {
    public static function testMethod() {
        $testInstance = new TestClass();
        $testClosure = function() use ($testInstance) {
            return $this === $testInstance;
        };

        $bindedTestClosure = $testClosure->bindTo($testInstance);

        call_user_func($bindedTestClosure);
        // should be true
    }
}

TestClass::testMethod();

2 个答案:

答案 0 :(得分:3)

PHP始终将父thisscope绑定到新创建的闭包。静态闭包和非静态闭包之间的区别在于静态闭包在{strong>创建时时具有scope(!= NULL)但不是this。 “顶级”关闭既没有this也没有scope

因此,在创建闭包时必须摆脱范围。幸运的是bindTo允许这样,即使是静态闭包:

$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
$m();

答案 1 :(得分:1)

Closure::bindTo documentation

看起来可能无法做到这一点
  

静态闭包不能有任何绑定对象(参数newthis的值应该为NULL),但是这个函数可以用来改变它们的类范围。