php如何在定义对象之前在闭包中获取引用


php how to get reference in closure before the object is defined

我有一个类,在类A中有一个test函数。我想在$invoker's函数体中获得$server的引用。我使用Closure获得$this的引用,但我无法使用闭包获得$server的引用,因为$server是在定义$inovker之后定义的。

谢谢。

class A {
    public test() {
        $self = $this;
        $invoker = function () use($self){
            $self.test2(); // ok, no problem, Closure is my best friend
            $server.someMethod(); //Error, How to access $server here?
        }
        $server = new B($invoker);
    }
    public test2(){
        echo "Thank you";
    }
}

这有点像鸡蛋问题。由于PHP从上到下进行处理,所以这是不可行的。您所能做的就是创建一个全局变量来保存$server。您将这个变量传递给调用者,但只有在调用了类B之后,您才能使用全局变量。我不建议这样做,因为您依赖于未初始化的变量。这看起来像是你在PHP中尝试一些C逻辑。