Error Identifier: generics.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 MyTrait
{
}
/**
* @template T
*/
interface Collection
{
}
/**
* @implements Collection<MyTrait>
*/
class MyCollection implements Collection
{
}
Why is it reported? #
A trait is being used as a type argument in a generic type. Traits cannot be used as types in PHP – they cannot be instantiated, used in type declarations, or referenced with instanceof. Using a trait as a generic type argument is invalid because PHPStan cannot reason about it as a proper type.
In the example above, MyTrait is a trait and is passed as a type argument to Collection<MyTrait>. This is not a valid type.
How to fix it #
Replace the trait with a class or interface that represents the intended type:
<?php declare(strict_types = 1);
-trait MyTrait
+interface MyInterface
{
}
/**
- * @implements Collection<MyTrait>
+ * @implements Collection<MyInterface>
*/
class MyCollection implements Collection
{
}
Or create an interface that the trait’s users implement and use that as the type argument:
<?php declare(strict_types = 1);
+interface HasMyTrait
+{
+}
+
trait MyTrait
{
}
/**
- * @implements Collection<MyTrait>
+ * @implements Collection<HasMyTrait>
*/
-class MyCollection implements Collection
+class MyCollection implements Collection, HasMyTrait
{
+ use MyTrait;
}
How to ignore this error #
You can use the identifier generics.trait to ignore this error using a comment:
// @phpstan-ignore generics.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: generics.trait