The spl_autoload_register Function
The spl_autoload_register function registers the given function as an implementation of the class autoloading method. When PHP encounters an undefined class, it sequentially calls all registered autoload functions, passing them the class name. The first parameter is the callback function for autoloading, the second parameter (optional) is whether to throw an exception on error, the third parameter (optional) is whether to add the function to the beginning of the queue.
Syntax
spl_autoload_register(callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]);
Example
Simple registration of an autoload function:
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.php';
}
spl_autoload_register('my_autoloader');
// Now we can create objects without explicit include
$obj = new MyClass();
?>
Example
Using an anonymous function for autoloading:
<?php
spl_autoload_register(function ($class) {
include 'lib/' . str_replace('\\', '/', $class) . '.php';
});
$obj = new Some\Namespace\MyClass();
?>
Example
Registering multiple autoload functions:
<?php
spl_autoload_register('autoloader1');
spl_autoload_register('autoloader2');
spl_autoload_register('autoloader3', true, true); // Add to the beginning of the queue
// PHP will call functions in order: autoloader3, autoloader1, autoloader2
$obj = new MyClass();
?>
See Also
-
the spl_autoload_functions function,
which returns autoloaders -
the spl_autoload_unregister function,
which removes an autoloader -
the class_exists function,
which checks a class