Reputation: 893
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.
Upvotes: 1
Views: 2521
Reputation: 21
This is what I do to avoid these warnings: I explicitly check the instance. So, just edit the function test:
public function test(): A
{
$instanceOfA = $this->returnBase('A');
if (!$instanceOfA instanceof A) {
throw new \Exception();
}
return $instanceOfA;
}
Here's the full code link with PSALM check: https://psalm.dev/r/4e9e8342fa
Upvotes: 0
Reputation: 632
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.
Upvotes: 4