Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top