What causes it
PHP does not allow two classes with the same name in one run. The error appears if you define a class twice, or if you include the same file more than once:
class MyClass {
// ... class definition
}
class MyClass { // This line causes the error
// ... another class definition
}
In a bigger project, the cause is often a file included twice, two files with the same class, or a plugin that clashes with a theme.
Fixes
1. Use include_once and require_once
These load a file only if it was not loaded before:
// Include the class definition only once
include_once 'MyClass.php';
Use require_once for files that are a must.
2. Use namespaces
Namespaces let two classes share a name if they live in different groups:
namespace MyCompany\Database;
class DatabaseConnection {
// ...
}
namespace MyCompany\Utility;
class DatabaseConnection {
// ...
}
3. Check if the class exists first
if (!class_exists('MyClass')) {
class MyClass {
// ... class definition
}
}
4. Rename one of the classes. If two classes of different libraries share a name, rename the one in your own code.
5. Check external libraries. Read their documentation. Some libraries are loaded in more than one way (for example by the plugin and by Composer).
Better habits
- Autoloading. Use a PSR-4 autoloader (Composer) so classes load only when needed.
- Static analysis. Tools such as PHPStan or PHP_CodeSniffer find duplicate classes.
Debugging tips
- Read the message. It names the class and the file and line of the second definition.
- Search the code. Search your project for
class MyClassto find all definitions. - WordPress. Turn off plugins one by one. A plugin that includes the same library as another one is a typical cause.
- Version control. Look at recent changes. A merge may have added a copy of a file.
Quick recap
- The same class is defined twice.
- Use
require_once, namespaces orclass_exists(). - Use Composer autoloading in bigger projects.