Question

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

Was it helpful?

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top