Error Identifier: instanceof.trait
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);
trait Loggable
{
public function log(string $message): void
{
echo $message;
}
}
function doFoo(mixed $value): void
{
if ($value instanceof Loggable) { // ERROR: Instanceof between mixed and trait Loggable will always evaluate to false.
$value->log('hello');
}
}
Why is it reported? #
PHP does not support using traits with the instanceof operator. Traits are a code reuse mechanism and do not define a type that can be checked at runtime. The instanceof check against a trait will always evaluate to false, regardless of the value being checked. This is a limitation of the PHP language, not just a PHPStan rule.
How to fix it #
Define an interface that declares the methods provided by the trait, and check against that interface instead:
<?php declare(strict_types = 1);
+interface LoggableInterface
+{
+ public function log(string $message): void;
+}
+
trait Loggable
{
public function log(string $message): void
{
echo $message;
}
}
function doFoo(mixed $value): void
{
- if ($value instanceof Loggable) {
+ if ($value instanceof LoggableInterface) {
$value->log('hello');
}
}
Classes using the trait should implement the interface:
<?php declare(strict_types = 1);
class MyClass implements LoggableInterface
{
use Loggable;
}
How to ignore this error #
You can use the identifier instanceof.trait to ignore this error using a comment:
// @phpstan-ignore instanceof.trait
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.trait
Rules that report this error #
- PHPStan\Rules\Classes\ExistingClassInInstanceOfRule [1]