简体   繁体   中英

require and require_once error in php

I am getting this error:

Fatal error: Cannot redeclare class Logger in C:\xampp\htdocs\Speakom\API\Logger.php on line 3

After changing all my require_once to require, this error still persists. Is there a way to prevent this error? why does it happen if I dont have require_once?

Is there a conditional statment that I could use to query whether the file was included already and then to include it?

One way to get around that error is to always declare your classes like this:

if(!class_exists('ClassName')) {
    class ClassName {
        // ...
    }
}

Of course, this doesn't solve your underlying issue of having the same class being imported multiple times. Check your application's logic and determine where it is being required.

Difference Between require and require_once

require 'file1.php';
require 'file1.php';

// versus...
require_once 'file1.php';
require_once 'file1.php';

In the first set, file1.php will be executed twice. In the second it will only be executed once. It really is as simple as that.

If both give you an error, then there may be an error in the file you are attempting to include. Remember that code inside included or required files executes in the same scope as the point that it was included.

The bug lies in the differences between require and require_once. Before, the require_once statements attempted to load the file once and any subsequent includes would do nothing. Now that you have changed it, you need to track down where in all of your includes you are doing the require. Remember, if you want it once, include it once and that's it. PHP keeps it all global so u dont need to include it in every file as long as one of your files in your include tree has that file included.

It is because you have two classes called Logger . Maybe you have copy-pasted class file but forgot to change the class name?

Did you check you don't actually have two Logger classes anywhere in your code?

check your code for

class Logger {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM