2017-02-23 23 views
0

是否有可能在PHP中创建配置类?
首先,你需要得到$ GLOBALS [“配置”]那么这被称为(例如)关键:
echo Config::get('database/main/username');如何在PHP中创建配置类文件

然后每一个“关键”爆炸时(一个PHP函数)由分隔符'/',然后每个'钥匙'再次被添加到主钥匙。主要关键是$GLOBALS['config']这是具有整个阵列的配置。


所以,每一个关键,应定义(试图 的foreach),并添加一个“计数”才知道什么是数组的计数


我的代码至今:

<?php 
    $GLOBALS['config'] = array(
     "database" => array(
      "username" => 'root', 
      "password" => '', 
      'host' => '127.0.0.1', 
      'name' => 'thegrades' 
     ), 
    ); 
    class Config 
    { 
     public static function get($key = null) 
     { 
      $count = 0; 
      $key = explode("/", $key); 
      if(count($key) > 1){ 
       $mainkey = $GLOBALS['config']; 
       foreach($key as $value){      
        $mainkey .= [$key[$count]]; 
        $count++; 
       } 
      } 
      return $mainkey; 
     } 
    } 
    var_dump(Config::get('database/host')); 
?> 
+0

为什么这个问题被downvoted? – Axis

+0

@Alex:所以你想解决配置类的改进吧? –

+0

我想学习如何做到这一点,不仅仅是为了让代码(btw是轴) – Axis

回答

2

在去罗马的路上,重构这一点,并采取你所需要的。

<?php 
$GLOBALS['config'] = array(
    "database" => array(
     "username" => 'root', 
     "password" => '', 
     'host' => '127.0.0.1', 
     'name' => 'thegrades' 
    ), 
); 
class Config 
{ 
    public static function get($key = null) 
    { 
     $keys = explode("/", $key); 
     $tmpref = &$GLOBALS['config']; 
     $return = null; 
     while($key=array_shift($keys)){ 
      if(array_key_exists($key,$tmpref)){ 
       $return = $tmpref[$key]; 
       $tmpref = &$tmpref[$key]; 
      } else { 
       return null;//not found 
      } 
     } 
     return $return;//found 
    } 
} 
var_dump(Config::get('database/host'));//127.0.0.1 
?>