Error Identifier: trait.duplicate
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);
// file: src/Helpers/MyTrait.php
namespace App\Helpers;
trait MyTrait
{
public function doSomething(): void
{
}
}
<?php declare(strict_types = 1);
// file: src/Legacy/MyTrait.php
namespace App\Helpers;
trait MyTrait
{
public function doSomethingElse(): void
{
}
}
Why is it reported? #
The same trait name is declared in multiple files. When PHP autoloading encounters two traits with the same fully qualified name, only one will be loaded. The other declaration is effectively dead code, which can lead to confusion and unexpected behaviour depending on which file gets loaded first.
How to fix it #
Rename one of the duplicate traits to give it a unique fully qualified name:
<?php declare(strict_types = 1);
// file: src/Legacy/MyTrait.php
-namespace App\Helpers;
+namespace App\Legacy;
-trait MyTrait
+trait LegacyTrait
{
public function doSomethingElse(): void
{
}
}
Or remove the duplicate declaration if it was unintentional.
How to ignore this error #
You can use the identifier trait.duplicate to ignore this error using a comment:
// @phpstan-ignore trait.duplicate
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: trait.duplicate
Rules that report this error #
- PHPStan\Rules\Classes\DuplicateClassDeclarationRule [1]