base classes:
abstract class A
{
public function methodA() { echo __FUNCTION__.'<br>'; }
}
class B extends A
{
public function methodB() { echo __FUNCTION__.'<br>'; }
}
so far so good. A factory which can create any of them:
class Factory
{
/**
* @return A
*/
public static function createAorB()
{
return new B();
}
}
phpdoc is right, since it say "return something comes from A".
Now the tricky part comes:
class OwnClass
{
/**
* @var A
*/
protected $var;
public function __construct()
{
$this->var = \Factory::createAorB();
}
}
class OwnClassB extends OwnClass
{
public function callMe()
{
$this->var->methodA();
$this->var->methodB(); // this will also run, but IDE wont autocomplete with this method
}
}
(new OwnClassB())->callMe();
this will run for sure, but check for the methodB() calling. IDE wont autocomplete with this method. How to tell that var is now B, not A with phpDoc?
@return Ais actually correct, when you're returningB? PHPStorm (at least) would properly autocomplete if you had@var Bon yourprotected $varvariable... (tested and proven in PHPStorm. Lints properly, and auto-completes properly with this one change).Ais part of the inheritance chain ofB. The phpdoc only says that the method will return a class conforming to the definition of class A. B does that (since it extends A). Which is also the reason why PHPStorm won't autocomplete - since you can't assume thatmethodBexists from the current hints.