在很多框架中都提供以数组的方式访问查询的结果集对象,操作遍历,比如,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;
}