Error Identifier: class.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);
// file1.php
class UserService
{
public function find(): void
{
}
}
// file2.php
class UserService
{
public function find(): void
{
}
}
Why is it reported? #
The same class name is declared in multiple files within the analysed codebase. PHP does not allow two classes with the same fully-qualified name. If both files are loaded at runtime, a fatal error will occur. Even if only one is loaded at a time (e.g., via autoloading), having duplicate declarations is confusing and error-prone.
How to fix it #
Remove the duplicate declaration, or rename one of the classes:
<?php declare(strict_types = 1);
// file2.php
-class UserService
+class AdminUserService
{
public function find(): void
{
}
}
Or place the classes in different namespaces:
<?php declare(strict_types = 1);
-// file2.php
-class UserService
+// file2.php
+namespace Admin;
+
+class UserService
{
public function find(): void
{
}
}
How to ignore this error #
You can use the identifier class.duplicate to ignore this error using a comment:
// @phpstan-ignore class.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: class.duplicate
Rules that report this error #
- PHPStan\Rules\Classes\DuplicateClassDeclarationRule [1]