PHP自动加载配置ArrayAccess类

ArrayAccess是PHP的类,可以把对象当成数组来使用访问。

Config.php   配置类
<?php
namespace IMooc;
 
class Config implements \ArrayAccess
{
  protected $path;
  protected $configs = array();
 
  function __construct($path){
    $this->path = $path;
  }
 
  function offsetGet($key){
    if (empty($this->configs[$key])){
      $file_path = $this->path.'/'.$key.'.php';
      $config = require $file_path;
      $this->configs[$key] = $config;
    }
    return $this->configs[$key];
  }
 
  function offsetSet($key, $value){
    throw new \Exception("cannot write config file.");
  }
 
  function offsetExists($key){
    return isset($this->configs[$key]);
  }
 
  function offsetUnset($key){
    unset($this->configs[$key]);
  }
}
index.php使用类:
//自动加载配置
$config = new \IMooc\Config(__DIR__ . '/configs');
var_dump($configs['controller']);

 

 
 
posted @ 2017-10-20 21:46  苍山雪洱海月  阅读(335)  评论(0)    收藏  举报