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?
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
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.
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:
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.
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.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')