PHP以数组的方式访问对象以及遍历

50 篇文章 2 订阅
6 篇文章 0 订阅

在很多框架中都提供以数组的方式访问查询的结果集对象,操作遍历,比如,Laravel,ThinkPHP,实现起来也很方便,一般是在对象的某个属性存放着记录数据,比如 attributes 私有属性。

使对象实现接口
1、ArrayAccess, 以数组的方式访问,实现方法 offsetExists,offsetGet,offsetSet,offsetUnset
2、IteratorAggregate,提供一个迭代器,实现方法 getIterator

代码:

<?php

class testObj implements ArrayAccess, IteratorAggregate
{
    private $attributes = [];

    public function __construct()
    {
        $this->attributes = [
            'name'  => 'rao',
            'age'   => 12,
            'phone' => '156',
        ];
    }

    public function offsetExists($offset)
    {
        return isset($this->attributes[$offset]);
    }

    public function offsetGet($offset)
    {
        return isset($this->attributes[$offset]) ? $this->attributes[$offset] : null;
    }

    public function offsetSet($offset, $value)
    {
        if (empty($offset)) {
            array_push($this->attributes[], $value);
        } else {
            $this->attributes[$offset] = $value;
        }

        return true;
    }

    public function offsetUnset($offset)
    {
        if (isset($this->attributes[$offset])) {
            unset($this->attributes[$offset]);
        }
        return true;
    }

    public function getIterator()
    {
        return new ArrayIterator($this->attributes);
    }

}

$obj = new testObj();
$obj['name'] = 'xi';
var_dump($obj['name']);

foreach($obj as $k => $v){
    echo $k.'=>'.$v.PHP_EOL;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值