Does anyone know what can cause this problem?
PHP Fatal error: Cannot redeclare class
You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
include_once "something.php";
to prevent multiple inclusions. It's very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another.
It means you've already created a class.
For instance:
class Foo {}
// some code here
class Foo {}
That second Foo would throw the error.
That happens when you declare a class more than once in a page.
You can fix it by either wrapping that class with an if statement (like below), or you can put it into a separate file and use require_once(), instead of include().
if (!class_exists('TestClass')) {
// Put class TestClass here
}
Use include_once(); - with this, your codes will be included only one time.
This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.
This error might also occur if you define the __construct method more than once.
Sometimes that happens due to some bugs in PHP's FastCGI.
Try to restart it. At Ubuntu it's:
service php-fastcgi restart
I had the same problem while using autoload like follows:
<?php
function __autoload($class_name)
{
include $class_name . '.php';
}
__autoload("MyClass1");
$obj = new MyClass1();
?>
and in other class there was:
namespace testClassNamespace;
class MyClass1
{
function __construct()
{
echo "MyClass1 constructor";
}
}
The sollution is to keep namespace compatibility, in my example namespace testClassNamespace; in both files.
Just adding;
This error can also occur if you by mistake put a function inside another function.
PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.
Just do one thing whenever you include or require filename namely class.login.php. You can include it this way:
include_once class.login.php or
require_once class.login.php
This way it never throws an error.
This function will print a stack telling you where it was called from:
function PrintTrace() {
$trace = debug_backtrace();
echo '<pre>';
$sb = array();
foreach($trace as $item) {
if(isset($item['file'])) {
$sb[] = htmlspecialchars("$item[file]:$item[line]");
} else {
$sb[] = htmlspecialchars("$item[class]:$item[function]");
}
}
echo implode("\n",$sb);
echo '</pre>';
}
Call this function at the top of the file that includes your class.
Sometimes it will only print once, even though your class is being included two or more times. This is because PHP actually parses all the top-level classes in a file before executing any code and throws the fatal error immediately. To remedy this, wrap your class declaration in if(true) { ... }, which will move your class down a level in scope. Then you should get your two traces before PHP fatal errors.
This should help you find where you class is being included from multiple times in a complex project.
Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini:
;includePaths.library = APPLICATION_PATH "/../library"
I hope this will help you.
Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").
I have encountered that same problem:
newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.
Or this tricks could help, if you d'ont have too much class in your library...
if( class_exists('TestClass') != true )
{
//your definition of TestClass
}
I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".
I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).
First solution:
Find in your whole project and make sure you have only one class XYZ.php.
Second solution:
Add a namespace in your class so you can use the same class name.
It actually means that class is already declared in the page and you are trying to recreate it.
A simple technique is as follow.
I solved the issue with the following. Hope this will help you a bit.
if(!class_exists("testClassIfExist"))
{
require_once("testClassIfExist.php");
}
i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.
You must use require_once() function.
Related
Does anyone know what can cause this problem?
PHP Fatal error: Cannot redeclare class
You have a class of the same name declared more than once. Maybe via multiple includes. When including other files you need to use something like
include_once "something.php";
to prevent multiple inclusions. It's very easy for this to happen, though not always obvious, since you could have a long chain of files being included by one another.
It means you've already created a class.
For instance:
class Foo {}
// some code here
class Foo {}
That second Foo would throw the error.
That happens when you declare a class more than once in a page.
You can fix it by either wrapping that class with an if statement (like below), or you can put it into a separate file and use require_once(), instead of include().
if (!class_exists('TestClass')) {
// Put class TestClass here
}
Use include_once(); - with this, your codes will be included only one time.
This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.
This error might also occur if you define the __construct method more than once.
Sometimes that happens due to some bugs in PHP's FastCGI.
Try to restart it. At Ubuntu it's:
service php-fastcgi restart
I had the same problem while using autoload like follows:
<?php
function __autoload($class_name)
{
include $class_name . '.php';
}
__autoload("MyClass1");
$obj = new MyClass1();
?>
and in other class there was:
namespace testClassNamespace;
class MyClass1
{
function __construct()
{
echo "MyClass1 constructor";
}
}
The sollution is to keep namespace compatibility, in my example namespace testClassNamespace; in both files.
Just adding;
This error can also occur if you by mistake put a function inside another function.
PHP 5.3 (an I think older versions too) seems to have problem with same name in different cases. So I had this problem when a had the class Login and the interface it implements LogIn. After I renamed LogIn to Log_In the problem got solved.
Just do one thing whenever you include or require filename namely class.login.php. You can include it this way:
include_once class.login.php or
require_once class.login.php
This way it never throws an error.
This function will print a stack telling you where it was called from:
function PrintTrace() {
$trace = debug_backtrace();
echo '<pre>';
$sb = array();
foreach($trace as $item) {
if(isset($item['file'])) {
$sb[] = htmlspecialchars("$item[file]:$item[line]");
} else {
$sb[] = htmlspecialchars("$item[class]:$item[function]");
}
}
echo implode("\n",$sb);
echo '</pre>';
}
Call this function at the top of the file that includes your class.
Sometimes it will only print once, even though your class is being included two or more times. This is because PHP actually parses all the top-level classes in a file before executing any code and throws the fatal error immediately. To remedy this, wrap your class declaration in if(true) { ... }, which will move your class down a level in scope. Then you should get your two traces before PHP fatal errors.
This should help you find where you class is being included from multiple times in a complex project.
Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini:
;includePaths.library = APPLICATION_PATH "/../library"
I hope this will help you.
Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").
I have encountered that same problem:
newer php version doesn't deal the same with multiple incluse of the same file (as a library), so now I have to change all my include by some include_once.
Or this tricks could help, if you d'ont have too much class in your library...
if( class_exists('TestClass') != true )
{
//your definition of TestClass
}
I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".
I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).
First solution:
Find in your whole project and make sure you have only one class XYZ.php.
Second solution:
Add a namespace in your class so you can use the same class name.
It actually means that class is already declared in the page and you are trying to recreate it.
A simple technique is as follow.
I solved the issue with the following. Hope this will help you a bit.
if(!class_exists("testClassIfExist"))
{
require_once("testClassIfExist.php");
}
i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.
You must use require_once() function.
I know this has been answered before and why this is caused. However, in my case, the problem is happening only on MacOS Lion (10.7) which is on php 5.3.6. The same code base is running on my windows 7 machine which is on php 5.3.8.
I have used require_once all over the place. The code fragment that seems to be causing the problem is:
class DbBase
{
...
}
in a file that is included from multiple files. However the error disappears if I wrap the class declaration inside of:
if (class_exists('DbBase') != true)
{
class DbBase
{
...
}
}
I have this scenario:
File DBBase.php:
defines Class DBBase
File A_DB.php:
require_once("DBBase.php")
File B_DB.php:
require_once("DBBase.php")
File foo.php:
require_once("A_DB.php")
require_once("B_DB.php)
So the file DBBase.php does get included twice. Does it?
Any insight is appreciated.
I was having the same error. However, it wasn't related to 'declare a single class multiple times'. It was because I've made a backup of the class like this:
class.shipping.php
class.shipping_092512_bk.php
Then, I uploaded the backup file to the server. That caused the application to fail due to the two classes. So, I renamed the backup to something else without .php file extension 'class.shipping_092512.bk'. Problem solved.
This error occurs when you declare a single class multiple times instead of once ; The code below would throw that error.
class phpp{}
class phpp{}
It is unlikely that the behaviour is not the same on 5.3.6 and 5.3.8 as there haven't been any significant changes in classes and objects.
You should check for duplicated codes in the files you are requiring once. . .
EDIT :
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.
So in your case it is not being included multiple times, whereas it would if you use require or include.
However you should restructure your entire code to prevent class redeclaration's.
class lol{}
if(!class_exists("lol")){
class lol{
function ll (){
return "ss";
}
}
}
echo lol::ll();
You wouldnt be able to access that ^^ , since its still a redeclaration.
I started to use the PHP __autoload function and now I'm getting those weird Fatal error: Cannot redeclare class xxx errors.
It's weird since these errors occur on classes I don't even load with the autoload function. And I also use require_once to include the files.
I'm really puzzled about this. Anyone knows anything about this kind of errors when using autoload?
require_once/include_once only looks at the file name when they're trying to include a file, not a class name. So you can have class Foo in both Foo.php and B.php, and then you'll get that error.
I'm not sure how __autoload would cause you any problems, unless __autoload requires Foo.php because it needs class Foo, and you require B.php manually which redefines class Foo.
By the way, use spl_autoload_register instead of __autoload.
i had same situation .. all i changed was and its working for me
include('xxx.php');
to
require_once('xxx.php');
I am not pretend on the best answer. Just my thoughts.
__autoload() is deprecated in PHP 7.2 and will be possiblly deleted.
I found this way to upload/include files
//initialize a function which will upload files
function upload(){//you can call the function as you like
//your path to files goes here
}
spl_autoload_register('upload')//specify the function, where you include your files(in this case it's upload function
I've had this before, not sure what caused it though. Make sure you're using require_once/include_once rather than the normal versions for starters. I think the problem was related to using class_exists without telling it to skip autoloading (class_exists($name, false)) - are you doing this?
I found the problem. Apparently when it wanted to include Bank class, it took the "bank.php" file from the current directory ^^. Which is just the bank page, it should have include "src/model/Bank.php". I removed the current directory from the search list and it has been fixed.
So always make sure the autoload function is including the correct files. Good practice is too name your files more straightforward like class.Bank.php or class.User.php instead of Bank.php or User.php.
Thanks for your help and quick response anyway!
I'm getting this error:
Fatal error: Cannot redeclare class Customer
Then I added the following code:
if (!class_exists('Customer')) {
include('include/customer.class.php');
}
Why do I still get that error?
I have a file (file1.php) which has the Customer() class declared.
In file1.php I make an ajax call to file2.php
In file2.php I declare the Customer() class again.
In file2.php there is only 1 declaration of Customer() class.
Check if your server runs opcode cacher like APC - that's the cause of an error. I've runned into it recently.
Clearly due to the fact I issue:
if (!class_exists('Customer')) {
The class doesn't exist so the class itself is somehow duplicating itself.
I use this class in numerous other pages in the application without a problem.
I simply removed the whole thing:
if (!class_exists('Customer')) {
include('include/customer.class.php');
}
And it somehow worked which is preplexing!
If the class existed, the class file should never be included...
It doesn't exist therefore, the class is being included.
Once included, it says it's already included...
Very, very odd...
Well, it's working now... I guess i'll leave it be...
Use include_once(). If that still gives you an error, the problem is that you are declaring the class more than once in the file "include/customer.class.php"
http://php.net/include_once
The errors could be caused by a class defined multiple times, for example:
class Foo() {}
class Foo() {} // Fatal error
If you are not sure how many times your class will be included you can two things:
Use include_once() or require_once() in order to be sure that that file is required "once" only.
Write that code you provided every time you are including that file:
if (!class_exists('Customer')) {
include('include/customer.class.php');
}
I'd prefer the first though.
Your problem is the one described above. There must be a place where the class is declared multiple times. Without any code is hard to tell where.
Here's some references:
include_once()
require_once()
PHP: The Basics
I have trying to solve the error : Fatal error: Cannot redeclare class
I have been looking everywhere and I can't find where the class was instantiated.
Is there anyway I can print debug info about the existing instance of that class.
Chances are you are importing the file that declares the class more than once. This can be symptomatic of includes/requires getting out of control so you may need to simply your structure.
One alternative approach is to use autoload to load classes to avoid this kind of problem. Another is to only use include_once or require_once. I generally prefer to use require with a simple structure.
Yes, stupid php doesn't tell you where the class was declared. Try the following (immediately before fatal error line)
$r = new ReflectionClass("YourClassName"); echo $r->getStartLine();
You can find out, where an object was instantiated by using var_dump(debug_backtrace()); and looking at the call stack.