173

Does anyone know what can cause this problem?

PHP Fatal error: Cannot redeclare class

Machavity
  • 30,841
  • 27
  • 92
  • 100
Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • 11
    This can append with APC + autload see http://stackoverflow.com/questions/4575341/php-with-apc-fatal-errors-cannot-redeclare-class – gagarine Mar 04 '12 at 17:04
  • 6
    Use autoload, or you can also try `if(!class_exists('YourClass')){ include 'YourClass.php'; }` – Timo Huovinen Sep 18 '12 at 17:28

19 Answers19

319

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.

AaronLS
  • 37,329
  • 20
  • 143
  • 202
  • 10
    this was really help full! – Marci-man Aug 06 '11 at 17:49
  • 4
    [avoid include_once](http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html), it's slow, use something else instead, like [autoloading](http://php.net/manual/en/language.oop5.autoload.php) :) – Timo Huovinen Jan 26 '12 at 09:41
  • 21
    @Timo Based on benchmarks I've looked at, there will only be a noticeable difference of about 1 second if you have a file with 100,000 include_once's. You would be better off optimizing your DB access or other logic than prematurely optimizing your file includes using substandard techniques like master include files. The autoload feature doesn't perform significantly differently. Each functions differently, and are not interchangeably appropriate. You can use one for the other, but there are corner cases where they do not function the same. – AaronLS Sep 18 '12 at 05:19
  • 3
    @Timo To quote the page you linked "using __autoload() is discouraged and may be deprecated or removed in the future." – AaronLS Sep 18 '12 at 05:20
  • 1
    @AaronLS Can't edit comments on SO, the link also links to the [better example](http://www.php.net/manual/en/function.spl-autoload-register.php). I suggested it after reading APC's developers comments and how he hated include_once (I felt bad for him). Also the difference is beyond just performance. – Timo Huovinen Sep 18 '12 at 16:34
  • 1
    To find out the place where was the first class declaration use this answer: https://stackoverflow.com/a/2420104/1939671 – bumerang Aug 23 '19 at 14:39
119

It means you've already created a class.

For instance:

class Foo {}

// some code here

class Foo {}

That second Foo would throw the error.

whichdan
  • 1,897
  • 1
  • 14
  • 11
  • 76
    This answer is not as helpful as AaronLS's. I don't think the questioner would have asked the question if (s)he had written an obvious repetition like this (even in quite a complex situation). The include_once tip helps to clarify an obscure feature of PHP. – DavidHyogo Mar 20 '13 at 02:12
  • 2
    This error might also occur if you define the __construct method more than once. – Jack Trowbridge Sep 01 '13 at 21:27
  • 4
    Just use include_once('FooBar.php') to include your class. The name of the function is self-explanatory. – MataMix Feb 19 '14 at 13:49
  • 2
    AaronLS's answer is much higher rated, and you can find it [way down here](http://stackoverflow.com/questions/708140/php-fatal-error-cannot-redeclare-class/708150#708150). – qris Oct 07 '14 at 11:48
  • Way down here, as in - the answer directly below this. – Jayden Lawson May 15 '15 at 08:01
  • 1
    Actually this answers the question perfectly and it is timeless, AaronLS makes an assumption then attempts to solve the problem which can now be solved many better ways. – TarranJones May 11 '16 at 11:32
  • Another addendum - if you're using PSR-4 autoloading and the namespace in the file doesn't match the namespace used to resolve the class where you instantiate it, then you get this error. – HorusKol Dec 06 '17 at 02:57
58

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
}
Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Sam
  • 797
  • 1
  • 5
  • 10
20

Use include_once(); - with this, your codes will be included only one time.

animuson
  • 53,861
  • 28
  • 137
  • 147
farhad
  • 209
  • 2
  • 2
15

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.

Ajeesh
  • 151
  • 2
  • 2
  • Golden answer in here for me - I didn't even think PHP might have had the same class name as I was using! – Jamie M May 11 '16 at 12:16
12

This error might also occur if you define the __construct method more than once.

Yonic Surny
  • 451
  • 6
  • 15
8

Sometimes that happens due to some bugs in PHP's FastCGI.

Try to restart it. At Ubuntu it's:

service php-fastcgi restart
luchaninov
  • 6,792
  • 6
  • 60
  • 75
  • Ok, it's a solution but it doesn't correct the problem And in my case, the problem appears randomly one or two times by month. :( – SkaJess Jan 23 '15 at 08:24
  • @SkaJess - you can add restart command to crontab to restart hourly. dirty - but will assure that max downtime of your site will be 1 hour. – luchaninov Jan 24 '15 at 11:42
  • @how - it's not a good solution for me because php is falling down during the working day. I think that in one way that I'll add restart command daily during the night. In the second way, i ll consider to upgrade IIS and PHP. – SkaJess Jan 30 '15 at 13:04
6

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.

Jacob
  • 14,949
  • 19
  • 51
  • 74
3

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.

Juri Sinitson
  • 1,445
  • 1
  • 14
  • 18
3

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.

Tim Ogilvy
  • 1,923
  • 1
  • 24
  • 36
Asraful Haque
  • 1,109
  • 7
  • 17
3

Just adding;

This error can also occur if you by mistake put a function inside another function.

bretddog
  • 5,411
  • 11
  • 63
  • 111
2

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.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
1

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").

Konrad Morawski
  • 8,307
  • 7
  • 53
  • 91
1

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
}
Alexandre Mazel
  • 2,462
  • 20
  • 26
1

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");
}
mohitesachin217
  • 451
  • 5
  • 14
1

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.

Community
  • 1
  • 1
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130
1

You must use require_once() function.

Ashnet
  • 404
  • 5
  • 5
  • I looked at the other Answers in this thread, and it seems that [this](https://stackoverflow.com/a/708207/12695027), [this](https://stackoverflow.com/a/37918590/12695027) and [this](https://stackoverflow.com/a/27644404/12695027) also mentions `require_once()`. Can you explain how your Answer is different? – Scratte Nov 04 '20 at 22:16
1

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.

Anne
  • 26,765
  • 9
  • 65
  • 71
Praditha
  • 1,162
  • 5
  • 24
  • 45
0

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.

R T
  • 4,369
  • 3
  • 38
  • 49