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

Nat*_*iel 8 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();
Run Code Online (Sandbox Code Playgroud)

smi*_*hax 3

PHP 始终将父闭包绑定thisscope新创建的闭包。静态闭包和非静态闭包的区别在于,静态闭包有scope(!= NULL) 但this创建时没有。“顶级”闭包既没有this也没有scope

因此,在创建闭包时必须摆脱作用域。幸运的是bindTo,即使对于静态闭包,也完全允许这样做:

$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
$m();
Run Code Online (Sandbox Code Playgroud)