注意:__autoload() 內的錯誤不能被 try-catch 捕獲。
| 代碼如下 |
複製代碼 |
function __autoload($class_name){ require_once(PATH.'/calsses/'.$class_name.'.php'); } $obj1 = new mycalss1(); |
註冊 __autoload() 自動調用的函數:
spl 程式碼程式庫在 PHP5.0 之後預設自動啟用
spl_autoload_register([callback]); //不將具體實現的載入代碼寫在 __autoload() 內,可使用該函數註冊回呼函數。
如果使用類的方法作為回呼函數需要傳入一個數組:
| 代碼如下 |
複製代碼 |
spl_autoload_register(array('class_name'|$obj,'method_name')); 例如: spl_autoload_register(array($this,'autoloadClass')); |
spl_autoload_register(array('YiiBase','autoload'));// YII 架構的自動載入類的實現, YiiBase 類實現了一個autoload 方法。 spl_autoload_register() 可以註冊多個載入函數,成功載入類檔案之前將逐個嘗試所有註冊的載入函數。這在不同的類使用不同邏輯來匯入類檔案的時候很有用。
spl_autoload_unregister(); //取消某個註冊的載入函數,參數與 spl_autoload_register() 相同.
spl_autoload_functions();// 以數組形式返回所有註冊的 __autoload() 函數
spl_autoload(class_name[,file_extentions]); // __autoload() 函數的預設實現。 spl_autoload_register() 被調用時如果沒有傳入 函數名,則預設使用該函數,該函數的執行規則是: 類名轉為小寫作為檔案名稱,傳入的 file_extentions(多個副檔名以逗號隔開,預設為 .inc 和 .php)為副檔名,根據得到的檔案名稱嘗試在 php.ini 內設定的 include paths 中搜尋。
spl_autoload_call(class_name);//手動調用所有註冊的 __autoload() 函數來主動載入類檔案
spl_autoload_extentions([file_extentions]); //註冊或返回 spl_autoload() 中可以使用的副檔名,副檔名可以是 .a.b 這樣的形式,例如:
| 代碼如下 |
複製代碼 |
spl_autoload_extentions(".class.php"); spl_autoload_register(); //使用spl_autoload() 來嘗試自動載入類檔案 //這樣 spl_autoload('myclassName'); 會嘗試載入 檔案 "myclassName.class.php" . |
執行個體
1、將需要註冊的類放在一個數組中
| 代碼如下 |
複製代碼 |
<?php final class Utils {
private function __construct() { } public static function getClasses($pre_path = '/') { $classes = array( 'DBConfig' => $pre_path.'DBConfig/DBConfig.php', 'User' => $pre_path.'Model/User.php', 'Dao' => $pre_path.'Dao/Dao.php', 'UserDao' => $pre_path.'Dao/UserDao.php', 'UserMapper' => $pre_path.'Mapping/UserMapper.php', ); return $classes; } } ?> |
2、註冊數組
注意:步驟1中的類的路徑都是相對於init.php而言的,不是相對於Utils而言的,這是因為我們通過init.php裡的自動載入函數spl_autoload_register來require類的
| 代碼如下 |
複製代碼 |
<?php require_once '/Utils/Utils.php'; final class Init { /** * System config. */ public function init() { // error reporting - all errors for development (ensure you have // display_errors = On in your php.ini file) error_reporting ( E_ALL | E_STRICT ); mb_internal_encoding ( 'UTF-8' ); //registe classes spl_autoload_register ( array ($this,'loadClass' ) ); } /** * Class loader. */ public function loadClass($name) { $classes = Utils::getClasses (); if (! array_key_exists ( $name, $classes )) { die ( 'Class "' . $name . '" not found.' ); } require_once $classes [$name]; } } $init = new Init (); $init->init (); ?>
|
3、本例中在使用處test.php裡require init.php
| 代碼如下 |
複製代碼 |
<?php require_once 'Init.php'; $dao = new UserDao(); $result = $dao->findByName('zcl'); ?> |