3
votes

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?

5
Can you post some example code?Oliver Charlesworth
I get an error "Fatal error: Cannot redeclare randomstring() (previously declared in /var/www/vhosts/businessgame.be/httpdocs/new/functions/function.random.php:24) in /var/www/vhosts/businessgame.be/httpdocs/new/functions/function.random.php on line 34" The weird thing is, the error does not occur when I manually include a file Bank.php, but this file doesn't contain the function or doesn't even uses it :P. Raise your hand if you're clueless ^^KingIsulgard

5 Answers

6
votes

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.

4
votes

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

include('xxx.php');

to

require_once('xxx.php');
1
votes

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   
0
votes

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?

0
votes

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!