PHP预定义接口:ArrayAccess

简介
  • 提供像访问数组一样访问对象的能力的接口。

接口摘要
ArrayAccess {
/* 方法 */
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 )
}

目录
  • ArrayAccess::offsetExists — 检查一个偏移位置是否存在
  • ArrayAccess::offsetGet — 获取一个偏移位置的值
  • ArrayAccess::offsetSet — 设置一个偏移位置的值
  • ArrayAccess::offsetUnset — 复位一个偏移位置的值

代码演示

class Obj implements ArrayAccess
{
    private $container = [];

    public function offsetExists($offset): bool
    {
        echo '调用' . __METHOD__ . '方法' . PHP_EOL;
        echo print_r(func_get_args(), true);

        return isset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        echo '调用' . __METHOD__ . '方法' . PHP_EOL;
        echo print_r(func_get_args(), true);

        return $this->container[$offset] ?? null;
    }

    public function offsetSet($offset, $value)
    {
        echo '调用' . __METHOD__ . '方法' . PHP_EOL;
        echo print_r(func_get_args(), true);
        $this->container[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        echo '调用' . __METHOD__ . '方法' . PHP_EOL;
        echo print_r(func_get_args(), true);

        unset($this->container[$offset]);
    }
}

//实例化对象
$zhangsan = new Obj();

//赋值
$zhangsan['name'] = '张三';//调用Obj::offsetSet方法

//输出
echo $zhangsan['name'] . PHP_EOL;//调用Obj::offsetGet方法

//校验是否存在
isset($zhangsan['name']) . PHP_EOL;//调用Obj::offsetExists方法

//删除数组单元
unset($zhangsan['name']);//调用Obj::offsetUnset方法

猜你喜欢

转载自blog.51cto.com/phpme/2129715