0
我創建一個配置文件,看起來像:如何使用配置文件和自動加載明智
$conf['db_hostname'] = "localhost";
$conf['db_username'] = "username";
$conf['db_password'] = "password";
$conf['db_name'] = "sample";
$conf['db_type'] = "mysql";
$conf['db_prefix'] = "exp";
並將其保存爲config.php文件。
同樣自動加載磁帶機看起來像
class autoloader {
public static $loader;
public static function init()
{
if(self::$loader == NULL) {
self::$loader = new self();
}
return self::$loader;
}
public function __construct()
{
spl_autoload_register(array(this, 'library'));
spl_autoload_register(array(this, 'controller'));
spl_autoload_register(array(this, 'helper'));
spl_autoload_register(array($this, 'model'));
}
public function library($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/lib');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function controller($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/controller');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function helper($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/helper');
spl_autoload_extensions('.php');
spl_autoload($class);
}
public function model($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/model');
spl_autoload_extensions('.php');
spl_autoload($class);
}
}
- 我應該在哪裏放置這兩個文件?在根文件夾中?
- 這些
$config
將如何跨應用程序可用? - 我該如何在index.php中使用它們?我應該爲
$config
陣列創建一個類嗎? - 如何拒絕直接訪問config.php文件?
與你的問題沒有關係,但是如果你想讓自動加載器成爲Singleton,你應該減少'__construct()'的可見性,所以你不得不使用'autoloader :: init()'來獲得只有它的實例。 – jprofitt
爲你的配置文件,你可能想看看這個:http://php.net/manual/en/function.parse-ini-file.php – dqhendricks