ArrayAccess(数组式访问)接口:提供像访问数组同样访问对象的能力的接口。php
ArrayAccess { //检查一个偏移位置是否存在 abstract public boolean offsetExists ( mixed $offset ); //获取一个偏移位置的值 abstract public mixed offsetGet ( mixed $offset ); //设置一个偏移位置的值 abstract public void offsetSet ( mixed $offset , mixed $value ); //复位一个偏移位置的值 abstract public void offsetUnset ( mixed $offset ); }
若是咱们想像数组同样来访问你的PHP对象只须要实现ArrayAccess接口便可mysql
场景:假如我有一个User类,映射的是用户的信息,想经过数组的方式来访问和设置用户信息sql
<?php /** * Created by PhpStorm. * User: moell * Date: 16-10-30 * Time: 下午8:49 */ namespace User; class User implements \ArrayAccess { private $data = []; public function __construct() { $this->data = [ 'name' => 'moell', 'sex' => '男', 'email' => 'moell@gmail.com' ]; } /** * 检查指定字段数据是否存在 * * @param $offset * @return bool */ public function offsetExists($offset) { return isset($this->data[$offset]); } /** * 获取指定字段数据 * * @param $offset * @return mixed */ public function offsetGet($offset) { return $this->data[$offset]; } /** * 设置指定字段数据 * * @param $offset * @param $value * @return mixed */ public function offsetSet($offset, $value) { return $this->data[$offset] = $value; } /** * 删除指定字段数据 * * @param $offset */ public function offsetUnset($offset) { unset($this->data[$offset]); } } $user = new User(); //获取用户的email echo $user['email'].PHP_EOL; // moell@gmail.com //检查age是否存在 var_dump(isset($user['age'])); // bool(false) //设置age $user['age'] = 18; echo $user['age'].PHP_EOL; //18 //删除age unset($user['age']); var_dump(isset($user['age'])); // bool(false)
咱们的对象能够像数组同样操做了,是否是很神奇呢?数组
在咱们构建应用中,常常会经过一个配置文件变动程序的一个行为,经过ArrayAccess咱们会更轻松的实现。app
下面我带大家一块儿看看我是这么实现的ui
1. 在项目更目录下建立一个config目录
2. 在config目录下建立相应的配置文件,好比app.php 和 database.php。文件程序以下this
app.phpspa
<?php return [ 'name' => 'app name', 'version' => 'v1.0.0' ];
database.phpcode
<?php return [ 'mysql' => [ 'host' => 'localhost', 'user' => 'root', 'password' => '12345678' ] ];
3. Config.php实现ArrayAccessorm
<?php namespace Config; class Config implements \ArrayAccess { private $config = []; private static $instance; private $path; private function __construct() { $this->path = __DIR__."/config/"; } public static function instance() { if (!(self::$instance instanceof Config)) { self::$instance = new Config(); } return self::$instance; } 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('不提供设置配置'); } public function offsetUnset($offset) { throw new \Exception('不提供删除配置'); } } $config = Config::instance(); //获取app.php 文件的 name echo $config['app']['name'].PHP_EOL; //app name //获取database.php文件mysql的user配置 echo $config['database']['mysql']['user'].PHP_EOL; // root
若是你给我同样热爱PHP,欢迎加入QQ群:339803849一块儿讨论
文章转载说明出处,本文地址:http://moell.cn/article/29