在各类框架中,均可以看见它们很方便的读取配置文件,就好比ThinkPHP,laravel。它们的配置文件的格式相似以下:php
<?php return [ 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], ] ];
而后一个函数config('文件名.connections.mysql.driver')就能够读取值。这靠得是咱们PHP内置的预约义接口——ArrayAccess。mysql
只要你的类实现了这个预约义接口,即可以使用数组的方式访问类。这样说也许很差理解,让咱们来实现像laravel同样读取配置文件吧。laravel
<?php class Config implements ArrayAccess { private $path; private $config = []; private static $install; private function __construct() { //定义配置文件处于当前目录下的config文件夹中 $this->path = __DIR__.'/config/'; } //返回单例 public static function install() { if (! self::$install) { self::$install = new self(); } return self::$install; } public function offsetExists($offset) { return isset($this->config[$offset]); } public function offsetGet($offset) { if (empty($this->config[$offset])) { $this->config[$offset] = require $this->path.$offset.".php"; } return $this->config[$offset]; } //你的配置确定不想被外部设置或者删除 public function offsetSet($offset, $value) { throw new Exception('could not set'); } public function offsetUnset($offset) { throw new Exception('could not unset'); } } function config($keys) { $config = Config::install(); $keysArray = explode('.', $keys); $config = $config[$keysArray[0]]; unset($keysArray[0]); foreach ($keysArray as $key) { $config = $config[$key]; } return $config; } echo config('config.debug');
在当前文件夹中创建config文件夹,用config函数即可以读取各类配置了。sql
固然,强大的ArrayAccess接口还有更增强大的实现,原理仍是那句话,实现了ArrayAccess接口,你的类,便提供了数组访问的能力。数组