How to typehint context in an IDE?

∥☆過路亽.° 提交于 2021-02-08 15:55:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!