標籤:
__autoload()函數可以實現自動載入所需要的類
用法:
__autoload() 在執行個體化對象時,若沒有引入相關的檔案,就會自動調用這個方法來進行載入。
執行個體:
public function __autoload($className){ $actionPath ="E://project/LiB/Action/".$className.".class.php"; if(!file_exists($actionPath)) { echo $actionPath."路徑不存在"; } require_once($actionPath);}
spl_autoload_register()函數
作用:註冊自訂載入函數
比如在檔案中定義一個 loadfile()作為自訂載入函數,但是至少聲明或者定義這個函數後,在執行個體化對象時,程式並不會自動去運行loadfile()這個函數,而會自動運行__autoload()函數。而spl_autoload_register()函數就是讓程式在執行個體化一個對象時組自動調用loadfile()函數。
執行個體:
<?php class test { public function testLoad() { echo "這是test類中的testLoad方法"; } }?><?php spl_autoload_register(array("AutoLoad", "autoLoadCore"), ‘‘, true); //註冊自動載入方法 //定義自訂載入函數 public static function autoLoadCore($classname) { $classPath = "E://project/LiB/Action/".$className.".class.php"; if(!file_exists($classPath)) { echo $classPath."路徑不存在"; } require_once($classPath); } $test = new test(); $test->testLoad();?>
結果: 輸出:這是test類中的testLoad方法;
spl_autoload_register()有三個參數
第一個:array($classname,$method),是一個數組,數組有兩個元素,第一個元素表示自動載入方法所在的類,第二個表示自動載入方法的函數名
第二個參數:表示無法成功註冊時是否拋出異常,true/false
第三個參數:true/false,表示是否將函數註冊到自動載入函數隊列之首。
注意:1、spl_autoload_register()實際上建立了 autoload 函數的隊列,按定義時的順序逐個執行(至今我沒有成功實現逐個執行的功能,請各位指點)
2、若使用spl_autoload_register()註冊了新的自動載入函數,那麼原有的__autoload()函數將失效,若需使用__autoload()函數,需要通過spl_autoload_register()再次註冊__autoload()函數,方能在使用此函數
PHP 中的__autoload() 與spl_autoload_register()函數