This is a short guide on how to deal with the following PHP error:
Fatal error: Cannot redeclare function name (previously declared in /path/to/file.php:3) in /path/to/other-file.php on line 9
The fatal error above will appear if your code contains two or more PHP functions that have the exact same name. Unlike other programming languages such as Java and C++, PHP does not support Method Overloading. Instead, you must use default / optional function parameters.
Where was the first function defined?
If you read the error carefully, you should be able to see what the issue is. In the example above, the function name in question was already previously declared on LINE 3 in file.php. This led to a fatal error when we attempted to create another function with the exact same name on LINE 9 in other-file.php
Take a look at the following example:
function test(){ //do something } function test(){ //do something else }
If you attempt to run the code snippet above, a fatal error will be thrown and the script will be killed. This is because I created two separate functions with the name test.
OK, so how do I fix this error?
The fix depends on your PHP application and what you are attempting to achieve.
Rename the other function to something else.
If you do not need a function called test, then you could rename the second function to something else.
In the case above, we could do the following:
function test(){ //do something } function myTest(){ //do something }
As you can see, I simply renamed the second test function to myTest.
Check if the function name has already been used.
If you find yourself in a situation where the function name may or may not exist, then you can check to see if the name of the function has already been defined.
An example of this approach being assigned to the problem that we had above:
function test(){ //do something } if(!function_exists('test')){ function test(){ //do something } }
In the code snippet above, I used the function_exists function to check if test already exists as a function. Because it does exist in the example above, the second function is never created.
Fatal error: Cannot redeclare Classname::function.
Note that PHP class methods / functions must also abide by the same rule:
/** * Class called Test. */ class Test{ //Function 1 public function test(){ //do something } //Function 2 protected function test(){ //do something } } $test = new Test();
If you run the code above, it will result in the following error:
Fatal error: Cannot redeclare Test::test() in /path/to/file.php on line 14
This is because a PHP class cannot have two functions with the exact same name. Note that I used public on the first function and protected on the second function because I wanted to demonstrate how the visibility of the method does not matter in this case.
Hopefully, you found this guide to be informative!