PHP has a nifty way to automatically load classes without the need to explicitly include class files. There is also a performance benefit, since only the unnecessary class files are loaded.
The traditional way to autoload in PHP was to make use of the __autoload function. The problem with this function is that it can only be used once. So if another library adds an __autoload function, the first one will be overwritten. PHP 5 changed this with then new SPL (Standard PHP Library) autoloader functions.
Autoload functions are now added to a stack and called in order. To add a new function to the stack simply add the callback function with spl_autoload_register 1. For example:
1 2 3 4 5 | function my_autoloader( $classname ) { //do something here... } spl_autoload_register( 'my_autoloader' ); |
You can also use a class member to autoload. For example, lets say I wanted to create an Autoloader class, with a load member:
1 2 3 4 5 6 7 8 | class Autoloader { public static function load( $classname ) { //do something here... } } spl_autoload_register( array( 'Autoloader', 'load' ) ); |
Callback functions can be unregistered using spl_autoload_unregister 2.
If your current code has an __autoload function and you need to support it for legacy reasons, you must explicitly add the __autoload function to the stack.
If your code has an existing __autoload function then it must be explicitly registered on the __autoload stack. Failing to register it would mean that
1 2 3 4 | if( function_exists( '__autoload' ) ) { spl_autoload_register( '__autoload' ); } |
An example of a very simple autoloader:
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | final class Autoloader { public static function load( $classname ) { $classfile = __DIR__ . "/classes/{$classname}.php"; if( file_exists( $classfile ) ) { include $classfile; } } } spl_autoload_register( array( 'Autoloader', 'load' ) ); $test = ClassLoadedWithAutoloader(); |
ClassLoadedWithAutoloader.php
1 2 3 4 | class ClassLoadedWithAutoloader { //class content } |
In the first file, index.php, I create an object of the class ClassLoadedWithAutoloader, which is in the /classes/ClassLoadedWithAutoloader.php file, but I am never explicitly including it, the autoloader is doing this for me.