How can I use docblock hints with classes for $this variables?

3.1k views Asked by At

I'm using NetBeans as my IDE. Whenever I have some code that uses another function (usually a factory) to return an object, typically I can do the following to help with hinting:

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

However, when I use an object's property to store that class, I'm at a bit of a loss how to do the same, as trying to use @var $this->foo or @var foo will not carry the hinting through:

use Path\To\FooClass;

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
    }
}

I have tried in the docblock for the class, or using the inline comments above protected $foo or where foo is set to the instance.

The only workaround I have found so far is to:

public function bat()
{
    $this->foo = FactoryClass::get('Foo');

    /* @var $extraVariable FooClass */
    $extraVariable = $this->foo;

    $extraVariable-> // now has hinting.
}

I would really like to have the hinting be class-wide though, as many other functions could potentially use $this->foo, and knowing the class's methods and properties would be useful.

Surely there is a more straightforward way...

2

There are 2 answers

1
Dan Soap On BEST ANSWER

I cannot say how it works in Netbeans, but in PHPEclipse, you would add the hint to the declaration of the variable itself:

use Path\To\FooClass;

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
    }
}
0
drew010 On

Given

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
    }
}

The IDE is trying to get the declaraion from FactoryClass::get which probably has no docblock return type. The problem is if this factory method can return any number of classes, there isn't much you can do except for using your workaround.

Otherwise, it wont know the difference between FactoryClass::get('Foo') or FactoryClass::get('Bar') since those two calls most likely would return objects of different types.