php数组式访问借口ArrayAccess

来源:互联网 发布:informix查看端口 编辑:程序博客网 时间:2024/05/21 09:43

定义:

ArrayAccess 是PHP标准库(SPL)提供的一个接口,这意味着我们可以直接调用,该接口使得对对象的访问像数组一样。

接口的形式大概类似于如下:

interface ArrayAccess{    //判断元素是否存在    function offsetExists($offset);    //获取元素    function offsetGet($offset);    //设置元素    function offsetSet($offset, $value);    //销毁某个元素    function offsetUnset($offset);}
*上面段代码在开发中不用写

例子一 :

简单使用ArrayAccess

<?phpclass test implements ArrayAccess{private $config = [];public function __construct(){$this->config = ['name' => '清华大学',];}public function offsetSet($k,$v){$this->config[$k] = $v;}public function offsetExists($k){return isset($this->config[$k]);}public function offsetGet($k){return $this->offsetExists($k) ? $this->config[$k] : null;}public function offsetUnset($k){unset($this->config[$key]);}}

*实际开发中可使用单例模式

$test = new test;echo $test['name']; //清华大学$test['age'] = 111;var_dump($test);

以上就是ArrayAccess简单使用

玩完了简单使用是不是觉得不够过瘾

接下来带大家来一段高级使用


例子二:

使用过框架的童鞋一定会觉得奇怪, 那些配置文件config就是一个数组,然后实现配置文件自动加载,用ArrayAccess模仿一下:

class Config implements ArrayAccess{    protected $path;//配置文件所在目录    protected static $configs = [];//保存我们已经加载过的配置public static $ins;public static function getIns(){if(self::$ins !instanceof self){self::$ins = new self;}return self :: $ins;}    //传入我们的配置文件所在目录    function __construct($path)    {        $this->path = $path;    }    //获取数组的key    function offsetGet($key)    {        //判断配置项是否加载        if(!isset($this->configs[$key])){            $file_path = $this->path.'/'.$key.'.php';            $config = require $file_path;            self :: $configs[$key] = $config;        }        return self :: $configs[$key];    }    //设置数组的key    function offsetSet($key, $val)    {        //用这种方式只能修改配置文件,可不能在这里直接修改配置项        throw new \Exception("不能修改配置项!");    }    //检测key是否存在    function offsetExists($key)    {        return isset(self :: $configs[$key]);    }    //删除数组的key    function offsetUnset($key)    {        unset(self :: $configs[$key]);    }}我们在 Config.php 所在目录下 新建目录 configs ,并在configs 目录下新建文件 database.php,代码如下:<?php    $config = array(        'mysql' => array(            'type' => 'MySQL',            'host' => '127.0.0.1',            'user' => 'root',            'password' => 'root',            'dbname' => 'test',        ),        'sqlite' => array(            //...        ),    );    return $config;?>使用配置:$config = new Config(__DIR__.'/configs');$database_conf = $config['database'];var_dump($database_conf);







0 0
原创粉丝点击