Saving Some Time by Autoloading PHP Classes Upon Demand
The spl_autoload_register() function
This function is a part of the PHP Standard Library (shortly SPL) that is built into PHP since verson 5.0.
In the most basic and probably common way, when the name of your class definitions and the names of the files containing them are the same, apart that the files have the '.php' at the end, enabling the class autoloading capability is as simple as this:
function class_loader($class) {
require('classes/' . $class . '.php');
}
spl_autoload_register('class_loader');
Here you might need to change the path to a directory that holds your class definitions according to your directory structure.
Off course you can also define and use an anonymous function in place of class_loader() to avoid cluttering the global namespace, like so:
spl_autoload_register(function($class) {
require('classes/' . $class . '.php');
});
I don't like relying on relative paths, because things might stop working when a code snippet is moved up or down the directory tree, in my code I prefer to use a constant or a variable that holds a path to the directory that encompasses the project, let's say it's a constant named SITE_ROOT defined in the configuration file, so autoloader I'd normally use will have a slightly different definition:
spl_autoload_register(function($class) {
require(SITE_ROOT . '/classes/' . $class . '.php');
});
$p = new Page();
require(SITE_ROOT . '/classes/Page.php');
You can quickly see the productivity gains with this function when you need to use many different types of objects, and having to include a list of files before using them would become too much of unnecessary work.