PHP的ArrayAccess接口简介

最近在研究php微框架slim的源码,slim中的依赖注入基于pimple,于是又去学习了一下pimple。
对比之前自己写的依赖注入类,pimple有一个很新鲜的用法,不是采用

$container->session_storage = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};

而是以数组方式进行注入:

$container['session_storage'] = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};

看源码时才发现原来诀窍就在php5提供的ArrayAccess接口上。
php文档地址如下:http://www.php.net/manual/zh/class.arrayaccess.php
官方定义:提供像访问数组一样访问对象的能力的接口。
该接口主要定义了四个抽象方法:

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 ) #删除数据

下面以一个简单的例子来实际说明下该接口的使用:



class Container implements ArrayAccess
{
    private $s=array();

    public function offsetExists($key){
        echo "you're trying to check if something exist
"
; return array_key_exists($key, $this->s); } public function offsetGet($key){ echo "you're trying to get something
"
; return isset($this->s[$key]) ? $this->s[$key] : ''; } public function offsetSet($key, $value){ echo "you're trying to set something
"
; $this->s[$key] = $value; } public function offsetUnset($key){ echo "you're trying to unset something
"
; unset($this->s[$key]); } } $c = new Container(); $c['name'] = 'ben'; //调用了offsetSet echo $c['name']."
"
; //调用了offsetGet echo empty($c['age'])."
"
; //调用了offsetExists unset($c['name']); //调用了offsetUnset echo empty($c['name']);

执行结果如下:

you're trying to set something
you're trying to get something
ben
you're trying to check if something exist
1
you're trying to unset something
you're trying to check if something exist
1

你可能感兴趣的:(spl)