Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__autoload detecting and including interfaces

I am using __autoload in my script to include classes as needed. My script uses cues in the class name to find the file containing it. If it ends in model it is in the model directory, controllers are in the controller directory, etc. I am starting to implement interfaces, and so need to adjust my autoloader.

Ideally, when an object is created the autoloader would determine the file-name of the object, where it is stored, and include the file. Then it would interrogate that class for what interfaces it implements, and then include those files automatically.

Something like

function __autoload($classname){
    echo $classname;
    include ("classes/$classname.php");
    $interfaces = class_implements($classname,FALSE);
    foreach($interfaces as $name){
        if(!class_exists($name,FALSE)){
        include("interfaces/".$name."inter.php");
        }
    }
}

Except when I do that I get the error

Cannot redeclare __autoload() (previously declared in W:\xampp\htdocs\test\auto.php:5) in W:\xampp\htdocs\test\auto.php on line 11

is it not possible to do this in the __autoload()? Should I just continue relying on naming conventions to differentiate between types of objects and where they are stored?

like image 776
Tyson of the Northwest Avatar asked Nov 24 '25 09:11

Tyson of the Northwest


1 Answers

You cannot define a class, before the implemented interfaces are defined and additional any unknown interface will trigger the autoload function too. This means in line 3 when including the class it will trigger the autoload function again with the interfaces as $classname. Now when returning from the second __autoload()-call it will try to include the interfaces once more, which will fail because of "already defined".

Additional: Using __autoload() is deprecated against using spl_autoload_register()

like image 146
KingCrunch Avatar answered Nov 26 '25 21:11

KingCrunch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!