工程目錄如下:
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');
?>