加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 13:26:12 所属栏目:PHP教程 来源:网络整理
导读:是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包? 这就是我的意思…… ?phpclass TestClass { public static function testMethod() { $testInstance = new TestClass(); $testClosure = function() use ($testInstance) { return $this ==
是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包?

这就是我的意思……

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读