Wikipedia:Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. The opposite of lazy loading is eager loading
在使用PHP進行開發時,開發人員往往將一個類存放在單獨的一個檔案中,便於使用和管理。
但是在PHP5之前,每次使用一個類時,需要先將該檔案include或require進來,如果需要使用的類數量很多,那麼需要寫很多include或require語句,既麻煩又不便於維護。好在PHP5提供了一種lazy loading的機制,即autoload。
PHP5之前如果要使用class A:
require ('A.php');$a = A();
PHP5中在試圖使用未定義的類時會自動調用__autoload函數,可以通過編寫__autoload函數讓php自動載入類,而不必寫一個長長的包含檔案清單。
function __autoload($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } $a = new A();
當然,我們可以自訂__autoload載入類的規則。
此外,假如我們不想自動載入的時候調用__autoload,而是調用我們自己的函數(或者類方法),我們可以使用spl_autoload_register來註冊我們自己的autoload函數。
function loader($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register('loader'); $a = new A();
類方法:
class Loader { public static function loadClass($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register(array('Loader', 'loadClass')); $a = new A();