PHP Fatal error: Cannot redeclare class

2019-01-01 13:28发布

Does anyone know what can cause this problem?

PHP Fatal error: Cannot redeclare class

18条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 13:45

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
}
查看更多
孤独寂梦人
3楼-- · 2019-01-01 13:46

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.

查看更多
宁负流年不负卿
4楼-- · 2019-01-01 13:46

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
}
查看更多
后来的你喜欢了谁
5楼-- · 2019-01-01 13:47

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.

查看更多
宁负流年不负卿
6楼-- · 2019-01-01 13:48

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.

查看更多
何处买醉
7楼-- · 2019-01-01 13:48

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");
}
查看更多
登录 后发表回答