PHP有6个预定义接口。

QQ截图20200311170432.png
其中,数组式访问,即ArrayAccess。
简单来说,这个接口的作用是让我们可以像访问数组一样访问对象

接口源代码:

/**
 * Interface to provide accessing objects as arrays.
 * @link http://php.net/manual/en/class.arrayaccess.php
 */
interface ArrayAccess {
    /**
     * Whether a offset exists
     */
    public function offsetExists($offset);
    /**
     * Offset to retrieve
     */
    public function offsetGet($offset);
    /**
     * Offset to set
     */
    public function offsetSet($offset, $value);
    /**
     * Offset to unset
     */
    public function offsetUnset($offset);
}

可以看到接口中有四个方法

未实现ArrayAccess

<?php
/**
 * 未实现ArrayAccess
 */
class Obj
{
    public $attr = 'attr';
}
$obj =  new Obj();
echo $obj->attr;    //使用->调用对象的属性,没有问题 attr
echo $obj['attr'];    //使用['']数组方式调用对象的属性,报错:Cannot use object of type Obj as array 

错误:
QQ截图20200311172447.png

实现ArrayAccess

<?php
/**
 * 实现ArrayAccess
 */
class Obj implements ArrayAccess
{
    //检测属性值是否存在
    public function offsetExists( $offset ) 
    {
        echo "offsetExists() $offset<br/>";
    }
    //获取属性
    public function offsetGet( $offset ) 
    {
        echo "offsetGet() $offset<br/>";
    }
    //设置属性值
    public function offsetSet( $offset, $value ) 
    {
        echo "offsetSet() $offset = $value<br/>";
    }
    //删除属性值
    public function offsetUnset( $offset ) 
    {
        echo "offsetUnset() $offset<br/>";
    }
}
$obj = new Obj();
isset($obj['attr']);    //offsetExists() attr
$obj['attr'];            //offsetGet() attr
$obj['attr'] = '123';    //offsetSet() attr = 123
unset($obj['attr']);    //offsetUnset() attr

框架中常规用法

<?php
/**
 * 框架中常规用法
 */
class Obj implements ArrayAccess
{
    private $data = [
        'attr'    =>    '123'
    ];
    //检测属性值是否存在
    public function offsetExists( $offset ) 
    {
        return isset( $this->data[$offset] );
    }
    //获取属性
    public function offsetGet( $offset ) 
    {
        return $this->data[$offset];
    }
    //设置属性值
    public function offsetSet( $offset, $value ) 
    {
        $this->data[$offset] = $value;
    }
    //删除属性值
    public function offsetUnset( $offset ) 
    {
        unset( $this->data[$offset] );
    }
}
$obj = new Obj();
var_dump( isset($obj['attr']) );    //true
var_dump( $obj['attr'] );            //123
$obj['attr'] = '321';
var_dump( $obj['attr'] );            //321
unset($obj['attr']);                
var_dump( isset($obj['attr']) );    //false

如若时光萧瑟去丶
111 声望9 粉丝

weakChickenPeng.