php 資料庫配置從配置檔案獲取
阿新 • • 發佈:2019-01-03
新建配置檔案檔案dbconfig.php
<?php
return [
'HOST'=>'127.0.0.1',
'USERNAME'=>'root',
'PASSWORD'=>'root',
'DBNAME'=>'root',
'CHARSET'=>'utf8',
];
?>
新建config.php 檔案
<?php
header('content-type:text/html;charset=utf-8');
/**
* Class config 資料庫配置類
* 1.判斷檔案是否存在
* 2.判斷配置是否是否存在
* 3.快取配置
*/
class config
{
/**
* 用於取出單個數據
* @param $name dbconfig.php 陣列下標
* @param $file 檔案
*/
static public $conf=[];//儲存資源
static public function getFrist($name,$file){
//echo self::$conf[$file];
if(isset(self::$conf[$file])){//如果檔案已經引入 就直接從靜態陣列中取
return self::$conf[$file][$name];
}else{
$path = $file.'.php';
if(file_exists($path)){//判斷檔案是否存在
$conf = include_once $path;
if(isset($conf[$name])){
self::$conf[$file]=$conf;//將檔案資源儲存到我們的靜態陣列中
return $conf [$name];
}else{
throw new \Exception('檔案配置不存在...'.$name);
}
}else{
throw new \Exception('檔案不存在...'.$file);
}
}
}
/**
* 取出檔案所有配置
* @param $file
* @return mixed
*/
static public function getAll($file){
if(isset(self::$conf[$file])){//如果檔案已經引入 就直接從靜態陣列中取
return self::$conf[$file];
}else{
$path = $file.'.php';
if(file_exists($path)){//判斷檔案是否存在
$conf = include_once $path;
self::$conf[$file]=$conf;//將檔案資源儲存到我們的靜態陣列中
return $conf;
}else{
throw new \Exception('檔案不存在...'.$file);
}
}
}
}
//測試
//getFrist
//echo config::getFrist('HOST','dbconfig');
//echo "<br>";
//getAll
//$db_data= config::getAll('dbconfig');
//echo $db_data['HOST'];