Search code examples
phpnetbeanscode-hintingdocblocks

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


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


Solution

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