Working with PHP 8 Autoloading

Learn how developers build autoloading logic and register multiple autoloaders.

The basic autoloading class mechanism first introduced in PHP 5.1 works the same in PHP 8. The main difference is that the support for the global function __autoload(), deprecated in PHP 7.2, has been completely removed in PHP 8. Starting with PHP 7.2, developers were encouraged to register their autoloading logic using spl_autoload_register(), available for that purpose since PHP 5.1. Another major difference is how spl_autoload_register() reacts if unable to register an autoloader.

An understanding of how the autoloading process works when using spl_autoload_register() is critical to our work as developers. Failure to grasp how PHP automatically locates and loads classes will limit our ability to grow as developers and could have a detrimental impact on our career paths.

Before getting into spl_autoload_register(), let’s first have a look at the __autoload() function.

Understanding the __autoload() function

The __autoload() function was used by many developers as the primary source of autoloading logic. This function behaves much as a magic method does, and that’s why it’s called automatically, depending on the context. Circumstances that would trigger an automatic call to the __autoload() function include the moment when a new class instance is created but where the class definition has not yet been loaded. Further, if the class extends another class, the autoload logic is also invoked in order to load the superclass prior to the creation of the subclass that extends it.

Get hands-on with 1200+ tech skills courses.