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 {}
}
$obj = new MyTrait(); // error: Cannot instantiate trait MyTrait.
Why is it reported? #
Traits in PHP are not standalone classes and cannot be instantiated with the new keyword. A trait is a mechanism for code reuse — it provides methods that can be included in one or more classes using the use keyword. Attempting to instantiate a trait will result in a fatal error at runtime.
How to fix it #
Use the trait inside a class and instantiate that class instead:
trait MyTrait
{
public function doSomething(): void {}
}
+class MyClass
+{
+ use MyTrait;
+}
+
-$obj = new MyTrait();
+$obj = new MyClass();
How to ignore this error #
You can use the identifier new.trait to ignore this error using a comment:
// @phpstan-ignore new.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: new.trait
Rules that report this error #
- PHPStan\Rules\Classes\InstantiationRule [1]