Is it possible to bind an instance to a static closure, or to create a non-static closure inside of a static class method?
This is what I mean...
<?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 always binds the parent this
and scope
to newly created closures. The difference between a static closure and a non-static closure is that a static closure has scope
(!= NULL) but not this
at create time.
A "top-level" closure has neither this
nor scope
.
Therefore, one has to get rid of the scope when creating the closure. Fortunately bindTo
allows exactly that, even for static closures:
$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
$m();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With