ArrayAccess 的介绍与使用
1.简单介绍
官方介绍 :提供像访问数组一样访问对象的能力的接口。
平时我们可能看到这样一种依赖注入的形式:
$container->session_storage ='cookie_name';
但是pimple
里面却出现了这样类似的形式:
$container['session_storage']='cookie_name';
抱着一探究竟的心态,其实在其类里面继承了ArrayAccess
这样一个接口,而这个接口有四个方法:
public function offsetExists($offset);
public function offsetGet($offset);
public function offsetSet($offset, $value);
public function offsetUnset($offset);
具体讲解
我直接贴上我写的一个小demo:
class Message implements ArrayAccess
{
/**
* 判断偏移量是否存在
* @param mixed $offset
* @return mixed
*/
public function offsetExists($offset)
{
echo 'this is offsetExists';
return isset($this->$offset);
}
/**
* 获取偏移量的值
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
echo 'this is offsetGet';
return $this->$offset;
}
/**
* 设置偏移量
* @param mixed $offset
* @param mixed $value
* @return mixed
*/
public function offsetSet($offset, $value)
{
echo 'this is offsetSet ';
$this->$offset = $value;
}
/**
* 复位偏移量
* @param mixed $offset
* @return mixed
*/
public function offsetUnset($offset)
{
echo 'this is offsetUnset ';
unset($this->$offset);
}
}
$m = new Message();
$m['name'] = 'LaravelChen'; //调用了offsetSet
echo $m->name;//输出LaravelChen
echo $m['name']; //调用了offsetGet
empty($m['name']);//调用了offsetExists和offsetGet
unset($m['name']);//调用了offsetUnset
创建一个继承于ArrarAccess
的类,实现其四个方法,每个方法的意思已标明,下面是相应的输出结果:
this is offsetSet
LaravelCHen
this is offsetGet LaravelChen
this is offsetExists this is offsetGet
this is offsetUnset
总结
这样一来,我们就实现了将一个类变成既可以支持对象引用,又可以支持数组引用,Good!
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 5年前 自动加精
$m['name'] = 'LaravelChen'; //调用了offsetSet 为什么这么一写就调用offsetSet??