简体   繁体   中英

PHP __autoload Cannot redeclare

I started to use the PHP __autoload function and now I'm getting those weird Fatal error: Cannot redeclare class xxx errors.

It's weird since these errors occur on classes I don't even load with the autoload function. And I also use require_once to include the files.

I'm really puzzled about this. Anyone knows anything about this kind of errors when using autoload?

require_once / include_once only looks at the file name when they're trying to include a file, not a class name. So you can have class Foo in both Foo.php and B.php, and then you'll get that error.

I'm not sure how __autoload would cause you any problems, unless __autoload requires Foo.php because it needs class Foo , and you require B.php manually which redefines class Foo .

By the way, use spl_autoload_register instead of __autoload .

i had same situation.. all i changed was and its working for me

include('xxx.php');

to

require_once('xxx.php');

I am not pretend on the best answer. Just my thoughts.

__autoload() is deprecated in PHP 7.2 and will be possiblly deleted.

I found this way to upload/include files

//initialize a function which will upload files
function upload(){//you can call the function as you like
  //your path to files goes here
}

spl_autoload_register('upload')//specify the function, where you include your files(in this case it's upload function   

I've had this before, not sure what caused it though. Make sure you're using require_once / include_once rather than the normal versions for starters. I think the problem was related to using class_exists without telling it to skip autoloading ( class_exists($name, false) ) - are you doing this?

I found the problem. Apparently when it wanted to include Bank class, it took the "bank.php" file from the current directory ^^. Which is just the bank page, it should have include "src/model/Bank.php". I removed the current directory from the search list and it has been fixed.

So always make sure the autoload function is including the correct files. Good practice is too name your files more straightforward like class.Bank.php or class.User.php instead of Bank.php or User.php.

Thanks for your help and quick response anyway!

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