Error Identifier: instanceof.alwaysFalse
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class Dog {}
class Cat {}
function doFoo(Dog $dog): void
{
if ($dog instanceof Cat) { // ERROR: Instanceof between Dog and Cat will always evaluate to false.
echo 'This is a cat';
}
}
Why is it reported? #
The instanceof check will always evaluate to false because the type of the checked expression can never be an instance of the specified class. In this example, the parameter $dog is typed as Dog, which has no relationship to Cat (neither extends nor implements it), so the check is always false. This usually indicates a logic error, a wrong variable being checked, or a wrong class name.
How to fix it #
Check against the correct class:
<?php declare(strict_types = 1);
class Dog {}
class Cat {}
function doFoo(Dog $dog): void
{
- if ($dog instanceof Cat) {
- echo 'This is a cat';
+ if ($dog instanceof Dog) {
+ echo 'This is a dog';
}
}
Or widen the parameter type if the function should accept multiple types:
<?php declare(strict_types = 1);
class Dog {}
class Cat {}
-function doFoo(Dog $dog): void
+function doFoo(Dog|Cat $animal): void
{
- if ($dog instanceof Cat) {
+ if ($animal instanceof Cat) {
echo 'This is a cat';
}
}
How to ignore this error #
You can use the identifier instanceof.alwaysFalse to ignore this error using a comment:
// @phpstan-ignore instanceof.alwaysFalse
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: instanceof.alwaysFalse
Rules that report this error #
- PHPStan\Rules\Classes\ImpossibleInstanceOfRule [1]