PHP 5.1 and spl_autoload_register

Mar 31 2008

Since PHP 5.1 we have spl_autoload_register (since PHP 5.0 we are able to define __autoload function);

Since PHP 5, if you define a function called __autoload, it will be called each time that you try to access a class that doesn’t exist. When calling a static method as well as instantiating a new object of that class.

This allows us to load code implicitly and forget about including dependencies everytime and allowing us to have a lazy loading very lightweight without having to load stuff that we are not interested in.

The only problem with this LazyLoading is that it forces us to use classes.

To group useful functions that we usually use, we can always define a util class with a set of static methods. For example, I usually use a function that I call print_r_pre, that does the same as print_r, but so it can display fine in a web browser (using htmlspecialchars). That’s it, you can create an util class with that function as a static method:

class util {
    static function print_r_pre($v) {
        echo '<pre>' . htmlspecialchars(print_r($v, true)) . '</pre>';
    }
}

I’d put this, for example, in a file called util.php, in a folder created to use __autoloadfeature. For example: /core/classes/util.php.

And later I would put this in a file that I should manually include (supposing that this file is inside /core/):

function __autoload($class) {
    if (!file_exists($file = dirname(__FILE__) . '/classes/' . $class . '.php')) return;
    require_once($file);
}

Summarizing:

If you are using PHP 5 and you want to avoid tons of require_once. __autoloadsolutions are for you.