PHP Fatal error: Cannot redeclare ...
PHP Fatal error: Cannot redeclare ...
DodaTech
2 min read
The “Cannot redeclare” fatal error occurs when PHP encounters a second definition of a function or class that has already been defined. This is a hard error that stops execution immediately.
What It Means
PHP allows each function and class to be defined only once in a given request. If you attempt to define the same function twice — even with identical code — PHP throws a fatal error. The same applies to classes, interfaces, and traits.
Why It Happens
- File included multiple times — a file containing a function definition is
included orrequired twice. - Function defined conditionally but executed twice — a function inside a loop or conditional branch is evaluated more than once.
- Plugin or framework conflict — two extensions define the same function name.
- Manual
includeafter autoloader — Composer’s autoloader loads a class, then you try torequirethe same file manually. - Copy-pasted code — the same function definition exists in two different files that both get included.
How to Fix It
1. Use require_once instead of require or include
// ❌ Can cause "cannot redeclare" if included twice
require 'helpers.php';
require 'helpers.php';
// ✅ Prevents double inclusion
require_once 'helpers.php';2. Check for existing definition before declaring
if (!function_exists('formatDate')) {
function formatDate($timestamp) {
return date('Y-m-d', $timestamp);
}
}3. Find duplicate includes with debug backtrace
// Temporarily add this to find where the function is declared
$declared = get_defined_functions()['user'];
if (in_array('yourFunctionName', $declared)) {
$refl = new ReflectionFunction('yourFunctionName');
echo "Already defined in: " . $refl->getFileName();
}4. Restructure your autoloading
If using Composer, let the autoloader handle includes:
{
"autoload": {
"files": ["src/helpers.php"],
"classmap": ["src/"]
}
}Run composer dump-autoload after updating.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro