Tutorials

Help! Fatal error: Cannot redeclare function - PHP Tutorial

Views: 135448
Rating: 2/5
Votes: 8

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