Error Identifier: traitUse.class
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);
class Helper
{
public function help(): void
{
}
}
class MyClass
{
use Helper;
}
Why is it reported? #
The use statement inside a class body is attempting to use a class as if it were a trait. The use keyword in a class body is reserved exclusively for traits. Classes cannot be used with the use statement. This code will result in a fatal error at runtime.
How to fix it #
If the intent is to reuse functionality from the class, extend it instead:
<?php declare(strict_types = 1);
-class MyClass
+class MyClass extends Helper
{
- use Helper;
}
If inheritance is not appropriate, use composition:
<?php declare(strict_types = 1);
class MyClass
{
- use Helper;
+ private Helper $helper;
+
+ public function __construct()
+ {
+ $this->helper = new Helper();
+ }
}
Or convert Helper into a trait if code reuse via traits is the intended approach:
<?php declare(strict_types = 1);
-class Helper
+trait Helper
{
public function help(): void
{
}
}
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]