Error Identifier: parameter.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
{
public function doSomething(): void
{
}
}
function doFoo(MyTrait $param): void // error: Parameter $param of function doFoo() has invalid type MyTrait.
{
}
Why is it reported? #
Traits cannot be used as type declarations in PHP. Unlike classes and interfaces, traits are a code reuse mechanism and do not define a type that can be checked at runtime. Using a trait as a parameter type will cause a fatal error. PHP only allows classes, interfaces, and built-in types in parameter type declarations.
How to fix it #
Extract an interface from the trait and use it as the parameter type instead.
+interface MyTraitInterface
+{
+ public function doSomething(): void;
+}
+
trait MyTrait
{
public function doSomething(): void
{
}
}
-function doFoo(MyTrait $param): void
+function doFoo(MyTraitInterface $param): void
{
}
How to ignore this error #
You can use the identifier parameter.trait to ignore this error using a comment:
// @phpstan-ignore parameter.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: parameter.trait
Rules that report this error #
- PHPStan\Rules\Functions\ExistingClassesInArrowFunctionTypehintsRule [1] [2]
- PHPStan\Rules\Functions\ExistingClassesInClosureTypehintsRule [1] [2]
- PHPStan\Rules\Functions\ExistingClassesInTypehintsRule [1] [2]
- PHPStan\Rules\Methods\ExistingClassesInTypehintsRule [1] [2]
- PHPStan\Rules\Properties\ExistingClassesInPropertyHookTypehintsRule [1] [2]