首页 > 解决方案 > 类型提示如何与 Closure::call 一起使用?

问题描述

我创建了一个名为的函数foo,它调用\Closurebar.

Closure::call()这里的文档说该call方法“临时将闭包绑定到 newthis,并使用任何给定的参数调用它”。

在我的示例中,我没有任何参数,但确实baz从我正在调用调用的对象调用方法。执行代码时,它会按预期回显“Hello world”。但是,我的 IDE 无法检测到bazanonymus 函数中的方法,而是标记了一个警告:Method baz not found in A.

class A
{
    public function bar(): string
    {
        $b = new B();

        return $b->foo(function(){
            return $this->baz();
        });
    }
}

class B
{
    public function foo(\Closure $callback): string
    {
        $callback->call($this);
    }

    public function baz(): string
    {
        return "Hello world!";
    }
}

我可以添加这样的东西。

$b->foo(function(){
    /** @var B $this */
    return $this->baz();
});

但是,如果我运行像 php stan 这样的静态代码分析。然后它报告: Call to an undefined method A::baz().

因此,我的问题是:我应该如何newthis在我的匿名函数中引用,这甚至可能吗?

标签: phpclosuresphp-7.0

解决方案


推荐阅读