Redeclaring a class (in a lower directory)
I have the following error
Fatal error: Cannot redeclare class Database in /home/content/63/8026363/html/include/user_database.php on line 5
That links to the line
class Database
But I have not redeclared this anywhere I can see.
I've checked all the include files and still can't se开发者_StackOverflowe it.
I have now changed the name to user_database1.php which is DEFINITELY only included once in my WHOLE system and I am still getting the same message!
This only occurs in my root/admin directory. When I moved the file it occurs into the root directory and updated the include files from ../file.php to just file.php, it worked perfectly.
I can't understand why having the file.php in the /admin directory and using ../ to include files isn't working!
Can anyone offer any experience of this? Or a potential fix.
I'll provide some code from the top of the file in question..
<?php
include("../include/session.php");
include("../include/admin_database.php");
Clearly this is the problem but I can't understand why!
Hope someone can help !
(question has been updated significantly since a lot of the answers below were submitted)
If you included the file two times, theen it gets re-declared. Use include_once()
instead to prevent that easily.
If you are unsure where that class was originally declared, you can make use of the Reflection API to get the name of the file and the line of code:
$class = 'Database';
if(class_exists($class))
{
$oRefl = new ReflectionClass($class);
$message = sprintf('Class %s already defined in %s on line %s.', $class, $oRefl->getFileName, $oRefl->getStartLine);
throw new DomainException($message);
}
Place that before the line where you define the class Database
to find out which file was originally defining the class.
Check if php already defines a file called Database.php. Maybe you are using some framework or library which does.
You probably have included your database class more than once, a quick fix for this is to add something like this to the top of your class:
if(!class_exists('Database')){
class Database{
// so on
}
This ensures that your class is only defined once.
精彩评论