Cannot redeclare saveorder() (previously declared in :10) on line 71 - php

I am getting this error for re-declaring saveorder() however, I don't think I am?!?
Cannot redeclare saveorder() (previously declared in :10) on line 71
8.function saveOrder()
9.{
10. include 'tables.php';
11. $orderId = 0;
12. $shippingCost = 5;
...
68. }
69. echo $orderId;
70. return $orderId;
71. }

You could be including the file that contains the function more than once:
include 'file.php';
include 'file2.php';
file.php:
include 'file2.php';
Cannot redeclare saveorder() (previously declared in :10) on line 71
Either use include_once or require_once to make sure it doesn't happen (this can cause problems if you try to include it twice in two separate locations (like first in a file, then later inside a function for some reason, the second one will not work if you include the _once part).

You must be including the current file (where the lines are from) multiple times.
An easy fix is using
if (!function_exists('saveOrder')) {
function saveOrder() {...}
}
However, I recommend creating a new functions.php file, including in only once, and placing all functions there.

Either tables.php contains a function also called saveOrder(), or the file you posted actually IS tables.php. PHP can't have 2 functions with the same name in the same namespace.

this could also be caused be saveorder() being delcared inside another function that is called multiple times.
eg.
function func1()
{
function saveorder()
{
echo 'x';
}
saveorder();
}
for ($i=0;$i<2;++$i)
func1();

I think this must be a bug in PHP since where you have ":10" I get all sort of strange symbols that do not occur anywhere in my code - ie. one time it might be ":0", next time ":196870" and the next time "!qhsu89s3". I also find that if I wait around a bit before refreshing then it normally sorts itself out.
Not too encouraging I have to say, but I presume a problem with PHP on Windows.

Related

PHP priority functions declarations

I have a question on the way that functions are declared in PHP.
First test :
File "functions.php" => functions toto(){ return "1"; }
Main File
include("functions.php")
functions toto(){ return "main"; }
echo toto();
Second test
File "functions.php" => functions toto(){ return "1"; }
File "functions2.php" => functions toto(){ return "2"; }
Main File
include("functions.php")
include("functions2.php")
echo toto();
Results
The first test work and echo "main"
The second test doesn't work => fatal error "function toto already define"
I make complementary tests :
in first test : put the functions toto() before include doesn't change the result.
Create twice functions toto() in the main file create Fatal Error
Someone can explain me how exactly this work ?
Thanks for reading
The PHP statements from the include family do not copy-paste the content of the included file in the context of the includer. The inclusion happens at runtime.
In your first example, the function toto() defined in the main file is created during the compilation. Then, on the execution, the functions.php file is read and parsed. It generates an error because it attempts to define the function toto() that is already defined.
The same happens in the second example during the inclusion of functions.php. Also, you get the same error if you declare the function toto() two times in the main script.
Either way, the PHP functions and constants cannot be re-declared.
A quick quote from the documentation:
PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
You can check if a function is already defined (to avoid defining it again) by using the function_exists() PHP function:
function toto() { return 1; }
if (! function_exists('toto')) {
function toto() { return 2; }
}
Points to the topic
You can only name one function toto() else you get Fatal error: Cannot redeclare You can use if(!function_exists('toto')){ /*declaration*/ } to prevent that.
php complies a file complete before including next files, means all functions in a php will be declared, then includes are made. So if the first line includes a file that declares toto(), but the next line declares also toto(). The declaration in the include throw the Fatal error.
The only way to prevent this is for example wrap in the first file if(1){ } around the declaration, so know the Fatal Error comes not from the included file.
Test Case:
//file1.php
<?php
function toto(){ echo __FILE__; }
//file2.php
<?php
include 'file1.php';
function toto(){ echo __FILE__; }
toto();
Call:
php file2.php
Result:
Fatal error: Cannot redeclare toto() (previously declared in file2.php)
//file1.php
<?php
function toto(){ echo __FILE__; }
//file2.php
<?php
include 'file1.php';
if(1){
function toto(){ echo __FILE__; }
}
toto();
Call:
php file2.php
Result:
Fatal error: Cannot redeclare toto() (previously declared in file1.php)

Cannot redeclare function error

Fatal error: Cannot redeclare close() (previously declared in
E:\wamp1\wamp\www\sample.php:1) in E:\wamp1\wamp\www\sample.php on
line 9
function close($tb,$lr) {
echo '#close {
'.$tb.':-2.5%;
'.$lr.':-1.5%;
position:absolute;
cursor:pointer;
}';
}
close($close_tb, $close_lr);
When I run this script it says cannot redeclare close()(previously decalred in line 1) in line 9.
Even on error the values associate with $close_tb and $closr_lr are passed to the css.
What wrong am doing here? am just calling the function in line 9. Any help?
This means you already have a function called close().
Maybe you're including the same file twice or had a freak copypasta accident. Check your code for any double functions.
The fact that your script still works as expected likely means you have the exact same function twice.
Your error code means that you are defining the function close twice. The code you have provided does not illustrate this, however, you must have either included the file more than once, or may have duplicated your code.
Go through your code and ensure you are not including the function definition more than once.

Unable to access global variable in included file

I am having an unexpected issue with scope. The include documentation (also applies to require_once) says the required file should have access to all variable at the line it was required.
For some reason I am not able to access a class instantiated with global scope inside a function that was required in.
Would anyone know why? I am obviously missing something.
I got it working through a reference to $GLOBALS[], but I still want to know why it is not working.
UPDATE:
The error I am getting is:
Fatal error: Call to a member function isAdmin() on a non-object in <path>.php on <line>
Code:
$newClass = new myClass();
require_once("path to my file");
----- inside required file -----
function someFunction() {
$newClass->someMethod(); // gives fatal error. (see above).
}
Functions define a new scope, so inside a function you cannot access variables in the global scope.
Variable Scope
within user-defined functions a local
function scope is introduced. Any
variable used inside a function is by
default limited to the local function
scope
About included files, the manual states:
When a file is included, the code it
contains inherits the variable scope
of the line on which the include
occurs.
So if you include something in a function, the included file's scope will be that of the function's.
UPDATE: Looking at your code example edited into the question, global $newClass; as the first line of the function should make it working.
$newClass = new myClass();
require_once("path to my file");
----- inside required file -----
function someFunction() {
global $newClass;
$newClass->someMethod();
}
Be aware though that using global can quickly make your code more difficult to maintain. Don't rely on the global scope, you can pass the object to the function as a parameter, or use a Singleton/Registry class (some tend to argue against the latter, but depending on the case it can be a cleaner solution).
The included code doesn't have a scope different than the code surrounding it. For example:
function a() {
echo $b;
}
This will fail even if echo $b is in an included file. If you replace the above with:
function a() {
include 'file.php';
}
... and file.php contains:
echo $b;
... then it's the same thing as if you wrote:
function a() {
echo $b;
}
Think of it this way: whenever you use include / require, the contents of the included file is going to replace the include / require statement, just as if you removed the statement and pasted the contents of the file in its place.
It doesn't do anything else as far as scope is concerned.

Is there a way to avoid the "redeclared function" fatal error while defining functions within functions in PHP?

I've been implementing a certain plugin (dtabs) on my page in Wordpress but after upgrading to the latest version, I found that I now have an error the 2nd time I call the main function called dtab_list_tabs().
The way it works is, the plugin gets include_once'd but the main function is called however many times you want to place tabs in your layout. I have 2 such calls to dtab_list_tabs().
Now, the problem is, for whatever reason the developer decided to include another function directly inside dtab_list_tabs() called current_tab(). Because it's declared within a function, apparently PHP tries to redeclare it as soon as you call the parent function the 2nd time, which doesn't make any sense to me.
PHP Fatal error: Cannot redeclare current_tab() (previously declared in .../wp-content/plugins/dtabs/dtabs.php:1638) in .../wp-content/plugins/dtabs/dtabs.php on line 1638
The code for that revision is at http://plugins.svn.wordpress.org/!svn/bc/208481/dtabs/trunk/dtabs.php
What I'm trying to figure out is whether there is a way to tell PHP that yeah... it has an internal function, which is a perfectly valid PHP paradigm as far as I know, so don't redeclare it and fail.
As for the situation at hand, I have removed current_tab() as it doesn't appear to be used.
You can use function_exists() to test if a function with that name has already been defined. If you make the definition conditional ( if(something) { function foo() {...} } ) php will "evaluate" the definition only when the condition is met.
function foo() {
if ( !function_exists('bar') ) {
function bar() {
echo 'bar ';
}
}
bar();
}
foo();
foo();
see also: http://docs.php.net/functions.user-defined
(But I'd try to avoid such things all together)
You can wrap your function declaration in an if statement. Use function_exists() to see if the function has been previously declared or not.
if(!function_exists('current_tab')) {
function current_tab() {
myMagicCode();
}
}
You can try this:
if (!function_exists('my_function')) {
function my_function() {
}
}
function_exists() - Return TRUE if the given function has been defined

"Fatal error: Cannot redeclare <function>"

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?
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.
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() {
........
}
}
You can check first whether the name of your function exists or not before you declare the function:
if (!function_exists('generate_salt'))
{
function generate_salt()
{
........
}
}
OR you can change the name of the function to another name.
You're probably including the file functions.php more than once.
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 had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone.
Maybe this will be helpful for someone.
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.
I would like to add my 2 cent experience that might be helpful for many of you.
If you declare a function inside a loop (for, foreach, while), you will face this error message.
I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.
Declare your function as a lambda expression (I haven't seen this solution mentioned):
$generate_salt = function()
{
...
};
And use thusly:
$salt = $generate_salt();
Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.
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')
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.
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.
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
I had this pop up recently where a function was being called prior to its definition in the same file, and it didnt have the returned value assigned to a variable. Adding a var for the return value to be assigned to made the error go away.
You have to deactivate the lite version in order to run the PRO version.
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.
or you can't create function in loop
such as
for($i=1; $i<5; $i++)
{
function foo()
{
echo 'something';
}
}
foo();
//It will show error regarding redeclaration

Categories