PHP類的自動載入

來源:互聯網
上載者:User

 

通常我們寫一個類如下:

a.php

 

class A<br />{<br /> public function __construct()<br /> {<br /> echo "hello world!";<br /> }<br />} 

 

page.php

require("a.php");<br />$a = new A(); 

 

 

我們是通過手工引用某個類的檔案來實現函數或者類的載入

但是當系統比較龐大,以及這些類的檔案很多的時候,這種方式就顯得非常不方便了

於是PHP5提供了一個::auotload::的方法

我們可通過編寫該方法來自動載入當前檔案中使用的類檔案

page.php

function __autoload($classname)<br />{<br /> $class_file = strtolower($classname).".php";<br /> if (file_exists($class_file)){<br /> require_once($class_file);<br /> }<br />}<br />$a = new A(); 

 

 

這樣,當使用類A的時候,發現當前檔案中沒有定義A,則會執行autoload函數,並根據該函數實現的方式,去載入包含A類的檔案

同時,我們可以不使用該方法,而是使用我們自訂的方法來負載檔案,這裡就需要使用到函數

bool spl_autoload_register ( [callback $autoload_function] ) 

page.php

function my_own_loader($classname)<br />{<br /> $class_file = strtolower($classname).".php";<br /> if (file_exists($class_file)){<br /> require_once($class_file);<br /> }<br />}<br />spl_autoload_register("my_own_loader");<br />$a = new A(); 

 

實現的是同樣的功能

自訂的載入函數還可以是類的方法

class Loader<br />{<br /> public static function my_own_loader($classname)<br /> {<br /> $class_file = strtolower($classname).".php";<br /> if (file_exists($class_file)){<br /> require_once($class_file);<br /> }<br /> }<br />}<br />// 通過數組的形式傳遞類和方法的名稱<br />spl_autoload_register(array("my_own_loader","Loader"));<br />$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.