Subscribe to PHP Freaks RSS

Help! Fatal error: Cannot redeclare function - PHP Tutorial

Print
by Eric Rosebrock on Feb 20, 2010 3:01:57 PM - 136,999 views

Hey Everyone, phpfreak here!

This is for the PHP beginners out there, and possibly a refresher for those of you who are writing functions. I've ran across issues such as "Fatal error: Cannot redeclare function" in my coding history. Mostly because I was lazy and wrote the function in a template file that was called by a loop to theme content. Sometimes though, code is written on major projects where the file defining the function has to have the function in that file. Therefore, simply defining a function in your code such as:

<?php
function foo($arg1) {
 return $arg1;
}
?>

Could get you into some trouble if that file is being looped through. You'd get that "Fatal error: Cannot redeclare function" error and your code will break. So, to get around this, we simply use the built in PHP Function: function_exists() to determine if we should define this function or not.

<?php
if(!function_exists('foo')){
    function foo($arg1) {
         return $arg1;
    }
}
?>

In a nutshell, you could think of the above statement like a caveman and say "IF NOT FUNCTION EXISTS foo THEN function foo..."

This should help you throughout your coding troubles. I'm a bit rusty, haven't written tutorials in a few years, so let me know if you have any thoughts or if you have any recommendations on other tutorials, feel free to post something!

//phpfreak
http://www.phpfreaks.com

Comments

MichaƂ Jarosz Feb 20, 2010 3:16:24 PM

Remember that there are other functions from 'something_exists()' family, that will protect you from similar errors.
class_exists()
interface_exists()

Eric Rosebrock Feb 20, 2010 3:49:28 PM

Michal - Good call! Thanks!

Brandon_R Mar 25, 2010 10:35:24 PM

Hopefully namespaces will soon fix this.

xeross May 6, 2010 2:07:38 PM

Could you give me an example where the function/class/interface can't be in a separate included file ?

That way you could get around it by using require_once/include_once.

@Brandon_R: I don't think namespaces would apply in this example

cadet018 Dec 8, 2010 3:21:48 AM

Remember, if you are using function_exists function in "if statement" (thats where it is suppose to be anyway) then if statement should be placed before calling the actual function.

Following code will give you "Fatal error: Call to undefined function foo()" because of involvement of "if statement"

<?php
//Calling function before declaring function, gives error
foo();

if(!function_exists("foo"))
{
function foo()
{
print "foo";
}
}
?>

To avoid this, declare the function before calling it
<?php
if(!function_exists("foo"))
{
function foo()
{
print "foo";
}
}

//Calling function after declaring function, works fine
foo();
?>

Note: If you are not using function_exists then don't worry about placement of function, php will take care of that

Add Comment

Login or register to post a comment.