问题
I am using Closure::call
(http://php.net/manual/en/closure.call.php) to call an external closure inside a class context.
Here's a simple repro:
class Foo {
private $bar = 'baz';
/**
* Executes a closure in $this context and returns whatever the closure returns.
*
* @param \Closure $closure
* @return mixed
*/
public function callClosureInThisContext(\Closure $closure) {
return $closure->call($this);
}
}
class Closures {
/**
* @return \Closure
*/
public function getClosureForFoo() : \Closure {
return function () {
// how do I tell my IDE that in this context $this is actually class Foo,
// and not the class Closures?
print $this->bar;
};
}
}
$foo = new Foo();
$closures = new Closures();
$foo->callClosureInThisContext($closures->getClosureForFoo()); // prints "baz"
This works as expected, but my IDE is of course, not happy, and is warning me about the "field bar
not found":
Can I somehow tell the IDE (in this case PhpStorm) that the closure is going to be used inside another class and that it should assume its context?
回答1:
try
/** @var $this Foo */
print $this->bar;
It will add autocomplete for class Foo additionally to Closure
来源:https://stackoverflow.com/questions/46894614/how-to-typehint-context-in-an-ide