通常我們寫一個類如下:
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();