0
0
PhpDebug / FixBeginner · 3 min read

How to Fix Cannot Redeclare Function Error in PHP

The cannot redeclare function error in PHP happens when you define the same function more than once. To fix it, ensure each function is declared only once by using include_once or require_once instead of include or require, or by checking if the function exists before declaring it.
🔍

Why This Happens

This error occurs because PHP does not allow two functions with the same name. If your code or included files declare a function twice, PHP stops and shows this error.

php
<?php
function greet() {
    echo "Hello!";
}

function greet() {
    echo "Hi!";
}
?>
Output
Fatal error: Cannot redeclare greet() (previously declared in ...)
🔧

The Fix

To fix this, avoid declaring the same function twice. Use include_once or require_once to include files only once. Alternatively, check if the function exists before declaring it.

php
<?php
if (!function_exists('greet')) {
    function greet() {
        echo "Hello!";
    }
}

greet();
?>
Output
Hello!
🛡️

Prevention

Always use include_once or require_once when including files with functions. Organize your code to avoid duplicate function names. Use tools like linters to catch redeclarations early.

⚠️

Related Errors

Similar errors include cannot redeclare class when a class is declared twice, and undefined function when a function is called but not declared. Fixes often involve checking for duplicates or correct file inclusion.

Key Takeaways

Use include_once or require_once to avoid loading the same function twice.
Check if a function exists before declaring it to prevent redeclaration errors.
Organize code to keep function names unique and clear.
Use linters or IDE warnings to catch duplicate declarations early.
Understand that PHP stops execution on redeclaration to protect your code.