Error Identifier: interface.traitUse
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 Timestampable
{
public function getCreatedAt(): string
{
return '2024-01-01';
}
}
interface EntityInterface
{
use Timestampable;
}
Why is it reported? #
Interfaces cannot use traits in PHP. Traits provide concrete method implementations, while interfaces are meant to define a contract of method signatures without implementations. Using a trait inside an interface is a language-level error that will cause a fatal error at runtime.
How to fix it #
Declare the required methods directly in the interface as abstract method signatures:
<?php declare(strict_types = 1);
interface EntityInterface
{
- use Timestampable;
+ public function getCreatedAt(): string;
}
If the trait’s functionality needs to be shared, use the trait in the implementing classes instead:
<?php declare(strict_types = 1);
interface EntityInterface
{
- use Timestampable;
+ public function getCreatedAt(): string;
+}
+
+class Entity implements EntityInterface
+{
+ use Timestampable;
}
Non-ignorable error #
This error cannot be ignored using @phpstan-ignore or the ignoreErrors configuration. Non-ignorable errors indicate code that would cause a crash or a fatal error at runtime, or a fundamental problem in the analysed code that must be addressed.
Rules that report this error #
- PHPStan\Rules\Classes\ExistingClassInTraitUseRule [1]