Páginas

2008/03/30

PHP 5.1 and spl_autoload_register


Since PHP 5.1 spl_autoload_register is available (and since PHP 5.0 we can define __autoload function).

On PHP 5 if you define the __autoload function, it will be called every time that you try to access a class that is not loaded/defined. Either, calling a static method or while creating an object of that class.

This behaviour allows us to load code implicity and avoids having to include dependencies every time. Also allows to have a very lightweight lazy loading without loading things we are not going to use.

The solely problem you can see to it, is that this Lazy Loading force us to use classes. (We won't be able to load functions lazily).

To group useful functions that we use commonly, we can define a class "util" with a set of static methods. For example, I'm using very offter a function that I have called print_r_pre, that performs the same as print_r but making it working on web (using <pre> and escaping characters with htmlspecialchars).
With that in mind, I could create a class "util" with that function as a static method:

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

I would put it, for example, in a file called util.php in a folder created to use with the __autoload feature. For example: /core/classes/util.php

After that, in a file that we have to include manually, something like this (assumming you are putting this code on _/core)):

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

Conclusion:

If you are using PHP 5 and you want to avoid lots of require_once calls. You can handle that problem using __autoload solutions: either spl_autoload_registers or __autoload.