PHP autoload機制(lazy loading)

來源:互聯網
上載者:User
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();
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.