如何将文档块提示与$this变量的类一起使用



我正在使用 NetBeans 作为我的 IDE。每当我有一些代码使用另一个函数(通常是工厂(返回对象时,通常我可以执行以下操作来帮助提示:

/* @var $object FooClass */
$object = $someFunction->get('BarContext.FooClass');
$object-> // now will produce property and function hints for FooClass.

但是,当我使用对象的属性来存储该类时,我有点不知所措,因为trying to use @var $this->foo or @var foo不会传递提示:

use PathToFooClass;
class Bar
{
    protected $foo;
    public function bat()
    {
        $this->foo = FactoryClass::get('Foo'); // Returns an instance of FooClass
        $this->foo //does not have hinting in IDE
    }
}

我已经尝试过该类的文档块,或使用上面的内联注释protected $foo或将foo设置为实例的位置。

到目前为止,我发现的唯一解决方法是:

public function bat()
{
    $this->foo = FactoryClass::get('Foo');
    /* @var $extraVariable FooClass */
    $extraVariable = $this->foo;
    $extraVariable-> // now has hinting.
}

我真的很想让提示是类范围的,因为许多其他函数可能会使用 $this->foo ,并且知道类的方法和属性会很有用。

当然还有更直接的方法...

我不能说它在 Netbeans 中是如何工作的,但在 PHPEclipse 中,您会在变量本身的声明中添加提示:

use PathToFooClass;
class Bar
{
    /**
     * @var FooClass
     */
    protected $foo;
    public function bat()
    {
        $this->foo = FactoryClass::get('Foo'); // Returns an instance of FooClass
        $this->foo // should now have hinting
    }
}

给定

class Bar
{
    protected $foo;
    public function bat()
    {
        $this->foo = FactoryClass::get('Foo'); // Returns an instance of FooClass
        $this->foo //does not have hinting in IDE
    }
}

IDE 正在尝试从可能没有文档块返回类型的FactoryClass::get获取声明。 问题是,如果此工厂方法可以返回任意数量的类,则除了使用解决方法外,您无能为力。

否则,它不会知道FactoryClass::get('Foo')FactoryClass::get('Bar')之间的区别,因为这两个调用很可能会返回不同类型的对象。

最新更新