您的位置:首页 > 编程语言 > PHP开发

PHP的ArrayAccess接口简介

2015-12-24 21:27 771 查看
最近在研究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 ) #删除数据


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

<?php

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

public function offsetExists($key){
echo "you're trying to check if something exist<br/>";
return array_key_exists($key, $this->s);
}

public function offsetGet($key){
echo "you're trying to get something<br/>";
return isset($this->s[$key]) ? $this->s[$key] : '';
}

public function offsetSet($key, $value){
echo "you're trying to set something<br/>";
$this->s[$key] = $value;
}

public function offsetUnset($key){
echo "you're trying to unset something<br/>";
unset($this->s[$key]);
}
}

$c = new Container();

$c['name'] = 'ben';                //调用了offsetSet
echo $c['name']."<br />";      //调用了offsetGet
echo empty($c['age'])."<br />";    //调用了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 php