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']);

PHP自动加载配置ArrayAccess类

 

 
 

相关文章:

  • 2022-12-23
  • 2021-10-21
  • 2022-02-10
  • 2021-09-28
猜你喜欢
  • 2022-01-01
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
  • 2022-02-17
相关资源
相似解决方案