微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/php/137374.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐