“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:18

You're probably including the file functions.php more than once.

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

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)

I think your facing problem at 3rd position the script including this file more than one time.So, you can solve it by using require_once instead of require or include_once instead of include for including your functions.php file -- so it cannot be included more than once.

查看更多
刘海飞了
4楼-- · 2018-12-31 14:20

means you have already created a class with same name.

For Example:

class ExampleReDeclare {}

// some code here

class ExampleReDeclare {}

That second ExampleReDeclare throw the error.

查看更多
若你有天会懂
5楼-- · 2018-12-31 14:21

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.

查看更多
荒废的爱情
6楼-- · 2018-12-31 14:22

you can check first if name of your function isn`t exists or not before you write function By

  if (!function_exists('generate_salt'))
{
    function generate_salt()
    {
    ........
    }
}

OR you can change name of function to another name

查看更多
只靠听说
7楼-- · 2018-12-31 14:29

Another possible reason for getting that error is that your function has the same name as another PHP built-in function. For example,

function checkdate($date){
   $now=strtotime(date('Y-m-d H:i:s'));
   $tenYearsAgo=strtotime("-10 years", $now);
   $dateToCheck=strtotime($date);
   return ($tenYearsAgo > $dateToCheck) ? false : true;
}
echo checkdate('2016-05-12');

where the checkdate function already exists in PHP.

查看更多
登录 后发表回答