【问题标题】:Binding object instances to static closures将对象实例绑定到静态闭包
【发布时间】:2013-05-27 14:48:41
【问题描述】:

是否可以将实例绑定到静态闭包,或者在静态类方法中创建非静态闭包?

这就是我的意思...

<?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 binding static closures instance


    【解决方案1】:

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

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

    $m=(new ReflectionMethod('TestClass','testMethod'))->getClosure()->bindTo(null,null);
    $m();
    

    【讨论】:

    • 所以你是说需要删除范围(不是这个 ehich 已经为空)以使其成为非静态闭包?
    【解决方案2】:

    看起来这可能是不可能的,来自Closure::bindTo documentation

    静态闭包不能有任何绑定对象(参数 newthis 的值应该是 NULL),但是这个函数仍然可以用来改变它们的类范围。

    【讨论】:

    • 这就是我的观点。如何在静态方法中创建非静态闭包?
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 2011-09-05
    • 2013-05-15
    • 2021-02-09
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多