Nate Higgins
Nate Higgins

Reputation: 2114

Binding object instances to static closures

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

Upvotes: 8

Views: 1669

Answers (2)

smilingthax
smilingthax

Reputation: 5734

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

Upvotes: 3

Orangepill
Orangepill

Reputation: 24655

Looks like this may not be possible, from Closure::bindTo documentation

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.

Upvotes: 1

Related Questions