是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包?
这就是我的意思…
<?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();
PHP总是将父this
和scope
绑定到新创建的闭包。静态闭包和非静态闭包的区别在于静态闭包具有scope
(!= NULL)而不是this
at create time。"顶级"闭包既没有this
也没有scope
。
因此,在创建闭包时必须去掉作用域。幸运的是,即使对于静态闭包,bindTo
也允许这样做:
$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
$m();
看起来这可能是不可能的,从Closure::bindTo文档
静态闭包不能有任何绑定对象(参数newthis的值应该是NULL),但是这个函数仍然可以用来改变它们的类作用域。