“Fatal error: Cannot redeclare

2018-12-31 13:38发布

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?

标签: php include
13条回答
看风景的人
2楼-- · 2018-12-31 14:30

or you can create function in loop

  • such as

    for($i=1; $i<5; $i++) { function foo() { echo 'something'; } }

foo();
//It will show error regarding redeclaration

查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 14:31

Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.

查看更多
不流泪的眼
4楼-- · 2018-12-31 14:32

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:
use:             include_once("functions.php");
instead of :  include ("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()  {
    ........
  }
}
查看更多
余生无你
5楼-- · 2018-12-31 14:33

In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.

This answer explains why you shouldn't use function inside function.

This might help somebody.

查看更多
妖精总统
6楼-- · 2018-12-31 14:36

I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.

require_once is also useful if the file you're attempting to include is essential.

查看更多
美炸的是我
7楼-- · 2018-12-31 14:38

I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')

查看更多
登录 后发表回答