Error Identifier: generics.traitBound
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 of MyTrait
*/
class Collection // error: invalid bound type MyTrait
{
}
Why is it reported? #
A @template tag uses a trait as its bound type or default type. Traits cannot be used as type bounds because they are not standalone types in PHP’s type system – they cannot be used in type declarations, instanceof checks, or as parameter/return types. A template type bound must be a class, interface, or a built-in type.
This applies to @template tags on classes, interfaces, traits, functions, and methods.
How to fix it #
Replace the trait with an interface or a class as the bound type:
<?php declare(strict_types = 1);
-trait MyTrait
+interface MyInterface
{
}
/**
- * @template T of MyTrait
+ * @template T of MyInterface
*/
class Collection
{
}
If you need to constrain the template type to classes that use a specific trait, consider extracting an interface that the trait’s users implement:
<?php declare(strict_types = 1);
interface Loggable
{
public function log(string $message): void;
}
trait LoggableTrait
{
public function log(string $message): void
{
// ...
}
}
/**
* @template T of Loggable
*/
class Collection
{
}
How to ignore this error #
You can use the identifier generics.traitBound to ignore this error using a comment:
// @phpstan-ignore generics.traitBound
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.traitBound
Rules that report this error #
- PHPStan\Rules\Generics\ClassTemplateTypeRule [1] [2]
- PHPStan\Rules\Generics\FunctionTemplateTypeRule [1] [2]
- PHPStan\Rules\Generics\InterfaceTemplateTypeRule [1] [2]
- PHPStan\Rules\Generics\MethodTagTemplateTypeRule [1] [2]
- PHPStan\Rules\Generics\MethodTagTemplateTypeTraitRule [1] [2]
- PHPStan\Rules\Generics\MethodTemplateTypeRule [1] [2]
- PHPStan\Rules\Generics\TraitTemplateTypeRule [1] [2]
- PHPStan\Rules\PhpDoc\IncompatiblePhpDocTypeRule [1] [2]
- PHPStan\Rules\PhpDoc\IncompatiblePropertyHookPhpDocTypeRule [1] [2]
- PHPStan\Rules\PhpDoc\IncompatiblePropertyPhpDocTypeRule [1] [2]