Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use spl_autoload_register?

Tags:

class Manage
{

spl_autoload_register(function($class) {
    include $class . '.class.php';
});
}

Say I have some code like the above. I chose to use the anonymous function method of loading classes, but how is this used? How exactly does it determine which '$class' to load?

like image 855
Steve Avatar asked Jun 21 '12 03:06

Steve


2 Answers

You can't put the code there. You should add the SPL register after your class. If you wanted to register a function inside the Manage class you could do:

class Manage {
    public static function autoload($class) {
        include $class . '.class.php';
    }
}

spl_autoload_register(array('Manage', 'autoload'));

However, as you demonstrated you can use an anonymous function. You don't even need a class, so you can just do:

spl_autoload_register(function($class) {
    include $class . '.class.php';
});

Either way, the function you specify is added to a pool of functions that are responsible for autoloading. Your function is appended to this list (so if there were any in the list already, yours will be last). With this, when you do something like this:

UnloadedClass::someFunc('stuff');

PHP will realize that UnloadedClass hasn't been declared yet. It will then iterate through the SPL autoload function list. It will call each function with one argument: 'UnloadedClass'. Then after each function is called, it checks if the class exists yet. If it doesn't it continues until it reaches the end of the list. If the class is never loaded, you will get a fatal error telling you that the class doesn't exist.

like image 163
Bailey Parker Avatar answered Nov 07 '22 06:11

Bailey Parker


How exactly does it determine which '$class' to load?

The $class is passed by php automatically. And it's the name of the class not declared yet, but used somewhere in runtime

like image 34
zerkms Avatar answered Nov 07 '22 06:11

zerkms



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!