在各類框架中,均可以看見它們很方便的讀取配置文件,就好比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接口,你的類,便提供了數組訪問的能力。數組