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

前端之家收集整理的这篇文章主要介绍了php – 将对象实例绑定到静态闭包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包?

这就是我的意思……

<?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总是将父级和范围绑定到新创建的闭包.静态闭包和非静态闭包之间的区别在于静态闭包具有范围(!= NULL),但在创建时不具有此范围.
“顶级”封闭既没有这个也没有范围.

因此,在创建闭包时必须摆脱范围.幸运的是bindTo允许这样,即使是静态闭包:

$m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
$m();
原文链接:https://www.f2er.com/php/137374.html

猜你在找的PHP相关文章