我创建了一个名为的函数foo
,它调用\Closure
在bar
.
Closure::call()这里的文档说该call
方法“临时将闭包绑定到 newthis,并使用任何给定的参数调用它”。
在我的示例中,我没有任何参数,但确实baz
从我正在调用调用的对象调用方法。执行代码时,它会按预期回显“Hello world”。但是,我的 IDE 无法检测到baz
anonymus 函数中的方法,而是标记了一个警告: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
在我的匿名函数中引用,这甚至可能吗?