What is Lazy Loading in PHP

Aug 07, 2009 Author: Developer

In PHP 5, using instantiating an undefined class in a static way would cause a critical error. This mean that you must include all of the class files that you need, better than loading them as they were needed. So that you don`t forget one or come up with complicated file inclusion mechanisms to reduce and 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 critical error.

function __autoload($class)
{
// Require PEAR-compatible classesrequire_once str_replace("_", "/", $class);
}
$obj = new Some_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’);
if (function_exists(’__autoload’)) 
{
spl_autoload_register(’__autoload’);
}

tags: Lazy loading

views 112511
  1. Add New Comment

gravatar
zoran
September 30,2009 at 00:17:25
just testing the comments
gravatar
Ben
June 23,2012 at 11:41:25
Nice article
gravatar
Obaid
March 28,2014 at 19:15:49
Awesome...