HomePHP Using the spl_autoload() Functions to Build Loader Apps in PHP
Using the spl_autoload() Functions to Build Loader Apps in 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 the passionate PHP developer that you probably are, you know that building file loading scripts is mostly a process that relies on the set of “include()/include_once()” and “require()/require_once()” functions, which you’ve surely used hundreds of times before.
Nevertheless, it’s feasible to create more efficient and elegant loading scripts by merging the functionality provided by the mentioned functions with that given by the Standard PHP Library (SPL). In truth, it is quite simple to develop short programs that include a specified resource or class using a recursive search through the file system. This process was discussed in depth in previous installments of this series.
But speaking more specifically, in the last tutorial I left off by explaining how to build a small file loading script with the handy “__autoload()” function, which is called by the PHP engine when it finds a reference to a class that hasn’t been included previously.
By giving a customized implementation to the “__autoload()” function, it’s possible to include classes in a transparent way, without having to explicitly call any PHP includes. However, as I mentioned before, the Standard PHP library comes bundled with some helpful functions, such as “spl_autoload(),” “spl_register_extension()” and “spl_autoload_register()” that allow you to either use a default implementation of the “__autoload()” function, or create a custom one for it.
This can be extremely useful when building reusable file loader programs. Thus, over this seventh episode of this series, I’m going to discuss how to use the aforementioned SPL functions to develop a few modular class loader scripts.
Now that you’re aware of the primary goal of this tutorial, it’s time to start learning how to use the Standard PHP library for including classes in a true effective manner. Let’s get going!