I have opinions

PHP autoload: The Good, the Bad and the Ugly

The autoload function is one of my favourite aspects of PHP. I’ve even blogged about it before. It makes writing code quicker and more reliable (no more typos or worrying about whether you forgot to include a class file) giving you more time to actually program.

But with todays Web we are often including libraries to help with specific tasks, à la API’s. Some of these can get quite bulky and complex which means they sometimes implement their own autoloader. Of course, this meant that our own autoloader could get overwritten causing all sorts of problems and head scratching.

Thankfully there is a way to add multiple autoloaders: spl_autoload_register(). This uses a FIFO approach, so if you have three different autoloaders it will try the first you declared, then the second, and finally the third. An example of how to use this can be found below.

Defining your autoloader as a standard function

// Set the autoloader to one of our functions
spl_autoload_register('myAutoloader');

// The autoloader function
function myAutoloader($class) {
    // Does the file exist?
    if (! file_exists(str_replace('_', '/', $className) . '.php')) {
        return false;
    }

    // The class exists, include the file
    include str_replace('_', '/', $className) . '.php';
}

Defining your autoloader in a class

You can also use the function to define your autoloader if it is declared inside a class. The implementation is just as simple:

// Set the autoloader to one of our functions
spl_autoload_register(class('MyClass', 'myAutoloader'));

// The autoloader class
class MyClass
{
    // The autoloader function
    public function myAutoloader($class) {
        // Does the file exist?
        if (! file_exists(str_replace('_', '/', $className) . '.php')) {
            return false;
        }

        // The class exists, include the file
        include str_replace('_', '/', $className) . '.php';
    }
}

The Bad and the Ugly

Of course there are a few downsides of having multiple autoloaders. The first being that it’s going to use more resources – more memory and more processing power as it loops through each of the autoloaders. Each autoloader might be checking to see if the file exists before including it which means, if you have three separate autoloaders, it’s going to check to run, potentially, three separate file_exists()‘s. When PHP 5.3 emerges and becomes commonplace this should hopefully be cured with namespaces, so that is something to look forward to.