I really have no idea what I did to cause this exception, but I have deduced that this problem is occurring only because I am including a PHP script. Here is the error it is throwing:
[Tue Jun 19 01:33:28 2012] [error] [client 127.0.0.1] PHP Fatal error: Cannot redeclare sql_connect() (previously declared in core.php:6) in core.php on line 9
Here is sql_connect()
:
function sql_connect(){
$a = mysql_connect("localhost", "user", "pass") or die(json_encode(array("failure"=>"SQL CON FAILURE: ".mysql_error()))); // Line 6
mysql_select_db("whoSync", $a);
return $a;
} //Line 9
More background: core.php
is not actually running any code, it merely defines functions. Now here is why it is weird: when I include core.php
in home.php
it throws that exception above. Including core.php
in any other file will not result in an error.
I am really good with PHP, but I have no idea what is happening. Thanks for any help.
Change your include
to include_once
or require_once
.
The issue is that you are calling/including a file multiple times which contains a function. The fatal error is thrown to prevent the function from being defined twice.
Explanation:
By using the *_once, PHP will only include the specified file once during the execution of the script. PHP does not support Method overloading (outside of the class scope) due to it's dynamic nature. A language like Java supports Overloading/Overriding of methods.
Let's say you have a file called home.php, about.php and sidebar.php. All three files call another file, database.php, which has a function called dbhandler().
dbhandler() has already been defined. If home.php is called, and it references sidebar.php, then database.php will be called twice. Using include_once/require_once, will only include database.php if it has not yet been called.
Hope this helps.
It means that core.php
is already loaded, for example, some other file includes it, and home.php
include that file will cause this. To prevent this, you could use include_once
or require_once
to make sure a file is included only once. Or you could make sure to include a file just once.