I use php __autoload state to automatically load classes. Today, I don’t know how a good program prompts Fatal error: Cannot redeclare class when running. It seems that the class is repeatedly defined. Let me analyze the solution below.
Error message
Fatal error: Cannot redeclare class….
It’s easy to understand from the literal point of view. It means that the class is repeatedly defined. I looked at my own code and found that it was caused by the existence of a class with the same name. Just change the class name.
Cause Analysis
1. A class with the same name is declared twice in the same file:
For example:
The code is as follows | Copy code |
代码如下 | 复制代码 |
class Foo {} // some code here class Foo {} ?> |
// some code here
class Foo {}
?>
An error will be reported at the second Foo.Solution: Remove the second Foo, or rename it.
代码如下 | 复制代码 |
if(class_exists('SomeClass') != true) { //put class SomeClass here } if(class_exists('SomeClass') != true) { //put class SomeClass here } |
In order to prevent repeated definitions, you can determine whether the class already exists when defining a new class:
The code is as follows | Copy code | ||||||||
if(class_exists('SomeClass') != true)
{
} if(class_exists('SomeClass') != true)
//put class SomeClass here } |
For example: for a certain class file some_class.php, in a.php
The code is as follows | Copy code |
include "some_class.php"; include "some_class.php"; |
代码如下 | 复制代码 |
class Com { } ?> |
The code is as follows | Copy code |
include "a.php"; include "some_class.php"; include "a.php"; include "some_class.php"; |
The code is as follows | Copy code |
class Com <🎜> { <🎜> <🎜> } <🎜> ?> |
At this time, it prompts Cannot redeclare class Com, indicating that this class is a built-in class in PHP. Cannot be used.
In addition, avoid using class names that are too popular, such as Com. This class may be normal in Linux but cannot run in Windows environment.
Let me remember another solution I found online. It may be useful in some situations. Remember it first
The code is as follows
|
Copy code
|
||||
www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632073.htmlTechArticleI use php __autoload state to automatically load classes. Today’s good program does not know how to prompt when running Fatal error: Cannot redeclare class. It seems that the class is repeatedly defined. Next...