auto load your php library classes with spl_autoload_register

Like all php programmers i have become more than familiar with the functions require, include, and require_once. All are for the inclusion and execution of scripts, or in simple terms a method to include classes or code contained in another file. An issue that faced when using these methods is knowing where to find the files from the current file, and also knowing all the files you need to include.

In php 5 the __autoload function was defined that enables a developer a way to define a function that if a class has not been loaded attempts to load it.  If for example you are creating an application that contains all classes in a folder called class you can define the __autoload function to attempt to require the php file in the classes folder named after the class.  This method works great if you are creating your own app not utilizing additional libraries that may utilize their own file hierarchy and loading scheme as only one __autoload function can be defined.

To enable the usage of multiple autoload functions spl_autoload_register was created.  The purpose of this is to the ability to register multiple functions that are attempted to load the class if it has not been loaded.  The main benefit being that multiple libraries can define their own autoload function and as a developer you only need to register their autoload functions in your files that utilize their libraries.

A sample basic function that can be used to autoload classes is outlined below. If we use the above example that all classes are stored in a file named after the class and contained in a folder called class. Also assume that our main library class is MDLib and autoload is a function defined in it.

public static function autoload($className)
    if (class_exists($className, false) || interface_exists($className, false)) {
        return false;
    $class = dirname(__FILE__) . "/class/" . $className . '.php';
    if (file_exists($class)) {
        require $class;
        return true;
    return false;

To register the autoload function we would simply need to require the main class then call spl_autoload_register passing the class and function to it.

/* Require Lib Main Class */
require_once(dirname(__FILE__) . '/lib/MDLib.php');
/* Register Auto Loader */
spl_autoload_register(array('MDLib', 'autoload'));

That is all there is to it. For further information you can visit the official php documentation. If you find yourself creating multiple classes for use in a library then using the spl_autoload_register function can save you and your end users time and effort in determining all the classes they need to register, also it could save load time as the classes won’t be loaded until the first time they are used.

// PHP //

Comments & Questions

Add Your Comment