Scenario
I'm using PHP7 type hinting to say that my function has return type City
.
public function getCityById(int $city_id) : City { ... }
In this function, I return the outcome of running a finder.
return $this->city_finder->findById($city_id);
But PhpStorm complains here, because the findById()
function returns AbstractModel
.
But I have class City extends AbstractModel
, so this isn't a problem. PhpStorm doesn't seem to recognize this, however, and highlights the return statement with a warning.
I don't want to mute this type of warning (disable inspection), because it is an important warning to have.
Question
Can I make PhpStorm recognize that this return statement will satisfy the return type?
Additional info
One workaround is to extract a variable, and annotate it, like so:
/** @var City $city */
$city = $this->city_finder->findById($city_id);
return $city;
At this point, it stops warning me about it, but it seems like the extra line should be avoidable since it only exists to mute a warning in the IDE.
The findById()
function is protected against returning the wrong type, because a Finder class is generated on a per-model basis.
$this->city_finder = $this->orm->getFinder(City::class);
//...
$city = $city_finder->findById(...);
PHPStorm is correct.
Your
findById()
returnsAbstractModel
and it is more broad thatCity
that you're trying to return. In a case if you'll receive fromfindById()
some other class that is also inherited fromAbstractModel
, but is not aCity
or its descendant - you will receive fatal error from PHP and it is what PHPStorm warns you about.You can workaround this by either adding annotation, as you do already or by explicitly checking
if ($city instanceof City) {return $city; }
. It may look slightly bloated by will be safe in runtime.