Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Fatal error: Cannot redeclare <function>"

Tags:

include

php

I have a function(this is exactly how it appears, from the top of my file):

<?php
//dirname(getcwd());
function generate_salt()
{
    $salt = '';

    for($i = 0; $i < 19; $i++)
    {
        $salt .= chr(rand(35, 126));
    }

    return $salt;
}
...

And for some reason, I keep getting the error:

Fatal error: Cannot redeclare generate_salt() (previously declared in /Applications/MAMP/htdocs/question-air/includes/functions.php:5) in /Applications/MAMP/htdocs/question-air/includes/functions.php on line 13

I cannot figure out why or how such an error could occur. Any ideas?

like image 918
fishman Avatar asked Dec 23 '09 16:12

fishman


2 Answers

This errors says your function is already defined ; which can mean :

  • you have the same function defined in two files
  • or you have the same function defined in two places in the same file
  • or the file in which your function is defined is included two times (so, it seems the function is defined two times)

To help with the third point, a solution would be to use include_once instead of include when including your functions.php file -- so it cannot be included more than once.

like image 192
Pascal MARTIN Avatar answered Oct 30 '22 02:10

Pascal MARTIN


Solution 1

Don't declare function inside a loop (like foreach, for, while...) ! Declare before them.

Solution 2

You should include that file (wherein that function exists) only once. So,
instead of :  include ("functions.php");
use:             include_once("functions.php");

Solution 3

If none of above helps, before function declaration, add a check to avoid re-declaration:

if (!function_exists('your_function_name'))   {
  function your_function_name()  {
    ........
  }
}
like image 76
T.Todua Avatar answered Oct 30 '22 00:10

T.Todua