Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 997
Nate Higgins Avatar asked May 31 '13 17:05

Nate Higgins


1 Answers

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();
like image 173
smilingthax Avatar answered Sep 22 '22 12:09

smilingthax