Lazy Loading
Prior to PHP 5, instantiating an undefined class, or using one of its methods in a static way would cause a fatal error. This meant that you needed to include all of the class files that you might need, rather than loading them as they were needed—just so that you wouldn't forget one—or come up with complicated file inclusion mechanisms to reduce the needless processing of external files.
To solve this problem, PHP 5 features an "autoload" facility that makes it possible to implement "lazy loading", or loading of classes on-demand. When referencing a non-existent class, be it as a type hint, static call, or attempt at instantiating an object, PHP will try to call the__autoload!) global function so that the script may be given an opportunity to load it. If, after the call to autoload(), the class is still not defined, the interpreter gives up and throws a fatal error.
function __autoload($class)
// Require PEAR-compatible classes require_once str_replace("_", "/", $class);
When instantiating Some_Class,__autoload() is called and passed "Some_Class.php"
as its argument. The function then replaces the underscores with forward slashes, and includes the file using require_once().
Using__autoload() is of great help when you are working with only one naming scheme; it allows lazy-loading of classes, so that classes that are never used are also never loaded. However, once you start mixing code and using different libraries (e.g.:
PEAR and some legacy application) you will rapidly run into cases that__autoload()
cannot handle without becoming too bulky and slow.
The Standard PHP Library (SPL), luckily, offers a simpler solution to this problem by allowing you to stack autoloaders on top of each other. If one fails to load a class, the next one in the chain is called, until either the class has been loaded, or no more autoloaders are part of the chain (in which case, a fatal error occurs).
By default, SPL uses its own autoloader, called spl_autoload(); this built-in function checks all include paths for filenames that match the name of the class that needs loading in lowercase letters, followed by .inc, .php, or the extensions specified using a comma-separated string as the only parameter to a call to spl_autoload_extensions().
Additional autoloaders can be added to the stack by calling spl_autoload_register(). The first call to this function replaces the__autoload()
call in the engine with its own implementation—this means that, if you already have a user-defined__autoload() you will need to register it with SPL in order for it to continue working:
spl_autoload_ register('spl_autoload');
spl_autoload_register('__autoload');
Post a comment