Reputation: 6197
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?
Upvotes: 1
Views: 553
Reputation: 11328
You can override inherited properties for PHPStorm's autocompletion:
/**
* @property B $var
*/
class OwnClassB extends OwnClass
{
//...
}
However, I personally think you're trying to solve the wrong problem. If you have a Factory class that returns either A
or B
, you shouldn't type hint the return value to A
. Instead, you should provide both:
class Factory
{
/**
* @return A|B
*/
public static function createAorB()
{
return new B();
}
}
Both options inform PHPStorm enough to let it show you both methods as autocomplete options, but the latter is accurate in terms of what the code actually does (well, not in this example, but given the function name I guess that's what your real-world implementation does).
Upvotes: 3