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 协议》,转载必须注明作者和本文链接
LaravelChen
本帖由系统于 5年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 1

$m['name'] = 'LaravelChen'; //调用了offsetSet 为什么这么一写就调用offsetSet??

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!