网中网 发表于 2017-4-3 12:06:46

php获取配置文件项的类

  配置文件形式(/app/config/env.php)
  return array(
  "default" => array(
  'host'=>'localhost',
  'email'=>'wsluozefeng@163.com'),
  "new"=>array('host'=>123, 'email'=>8888)
  );
  ==========================================================
  namespace lib;
  class config implements \ArrayAccess {
  static private $config;
  static private $_configPath;
  private $configarray;
  private function __construct() {
  $defaultDir = dirname($_SERVER['SCRIPT_FILENAME'])."/app/config/";  //该默认路径应该通过配置常量定义来获取的
  self::$_configPath = !empty( $configPath ) && is_dir( $configPath ) ? $configPath : $defaultDir;
  $dir     = new \RecursiveDirectoryIterator(self::$_configPath);  //获取路径下的所有文件和目录,不会递归输出
  $objects = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
  foreach( $objects as $fileName => $object ){
  $pathInfo = pathinfo($fileName);
  $this->configarray[$pathInfo['filename']] = require( $fileName );
  }
  }
  public static function instance() {
          if (self::$config == null){
              self::$config = new self;
          }
          return self::$config;
      }
  //检查一个偏移位置是否存在
  function offsetExists($index) {
  return isset($this->configarray[$index]);
  }
  //获取一个偏移位置的值
  function offsetGet($index) {
  return $this->configarray[$index];
  }
  //设置一个偏移位置的值
  function offsetSet($index, $newvalue) {
  $this->configarray[$index] = $newvalue;
  }
  //复位一个偏移位置的值
  function offsetUnset($index) {
  unset($this->configarray[$index]);
  }
  } 
  ==========================================================
  使用方式,通过集成了ArrayAccess接口,可以通过数组的形式来访问对象
  $config = lib\config::instance();
  print_r($config['default']);
页: [1]
查看完整版本: php获取配置文件项的类