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 14:01

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

查看更多
琉璃瓶的回忆
3楼-- · 2019-01-01 14:02

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.

查看更多
低头抚发
4楼-- · 2019-01-01 14:03

It means you've already created a class.

For instance:

class Foo {}

// some code here

class Foo {}

That second Foo would throw the error.

查看更多
千与千寻千般痛.
5楼-- · 2019-01-01 14:04

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

查看更多
牵手、夕阳
6楼-- · 2019-01-01 14:04

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.

查看更多
泛滥B
7楼-- · 2019-01-01 14:10

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.

查看更多
登录 后发表回答