HomePHP Page 3 - Using the spl_autoload() Functions to Build Loader Apps in PHP
Using the spl autoload extensions and spl autoload functions - PHP
Welcome to the seventh installment of an eight-part series on building loader applications in PHP. In this part, you will learn how to use the “spl_autoload(),” “spl_register()” and “spl_register()” functions to build a small file loader class. This class will be able to perform recursive searches through the file system to find a targeted resource.
As you saw in the preceding section, it’s pretty simple to implement the “__autoload()” function and build a class loading program very quickly. However, the Standard PHP library includes the “spl_autoload()” function, which has a default implementation for “__autoload().”
To help you understand how this function works, below I coded a whole new example. It shows how to dynamically include the “User” class that you saw before. The example in question looks like this:
// example on using the spl_autoload() function
// register file extensions
// default implementation for the __autoload() function
// load User class
// create instance of User class
$user = new User();
// display user data
If you closely examine the above script, you’ll realize how simple it is to work with the “spl_autoload()” function. First, the script uses the “spl_autoload_extensions()” to set up the appropriate order of the file extensions for which the PHP engine will look when attempting to load an given class. This can be very convenient for speeding up the whole loading process.
Finally, the “spl_autoload()” function is utilized to dynamically include the aforementioned “User” class via a default implementation of the previous “__autoload().”
Obviously, when it comes to creating class loaders in a few simple steps, the “spl_autoload()” function can be a real time-saver. But what if you need to define a custom method for including your classes? Well, that’s a really easy problem to solve, thanks to the existence of another function of SPL, called “spl_autoload_register().” As its name suggests, it permits you to register a custom callback function for autoloading classes.
In the last section of this tutorial I’m going to cover the use of this function in detail. Therefore, to learn more about it, click on the link below and keep reading.