I have some kind of factory where a method returns one of multiple possible classes but they all inherit the same parent class. The factory method returns always the same class when it gets the same parameter. So when I receive a class from the factory method I know the subclass beside the common parent class.
The problem is that PhpStorm shows me a warning when I try to set the @return
type to the child class.
Here an example:
abstract class Base {}
class A extends Base {}
class B extends Base {}
class T {
/**
* @param string $class
* @return Base
*/
public function returnBase($class)
{
switch ($class) {
case 'A':
return new A();
break;
// ... more cases ...
default:
return new B();
}
}
/**
* @return A
*/
public function test()
{
return $this->returnBase('A'); // Warning: "Return value is expected to be 'A', 'Base' returned"
}
}
I know in this example I could set the return type of returnBase()
to A|B
, but in my actual code I have much more classes. I don't want to set the return type of the test()
method to "Base" because the subclass might have unique methods/properties.
You can set a varibale type for each returnBase()
method like this :
/**
* @return A
*/
public function test()
{
/** @var A $a */
$a = $this->returnBase('A');
return $a;
}
Accroding to this article about PHP’s Garbage Collection, a redundant variable doesn't have any impact on memory consumtion.