Saving Some Time by Autoloading PHP Classes Upon Demand

Using the class autoloading function will not only make your life a bit easier when writing object oriented code, but also lessen input-output operations with files, therefore improving overall loading time of your application, as it will only load (include) files containing class definitions when there is need for it.

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'); });
Now it's time to use the autoloader, for example, let's create a new object of type Page:
$p = new Page();
What happens now is that PHP, behind the scenes, includes the apropriate file for us, as if we'd have the following line of code written ourselves prior to instantiating the object:
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.

Saving Some Time by Autoloading PHP Classes Upon Demand
This page was last updated on February 25, 2021
No comments have been posted so far
Leave a Comment