想操作对象一样来操作数组
<?php
class Test implements Iterator, ArrayAccess
{
private $position;
private $_items = array();
public function __construct()
{
$this->position = 0;
}
public function rewind()
{
$this->position = 0;
}
public function current()
{
return $this->_items[$this->position];
}
public function key()
{
return $this->position;
}
public function next()
{
++ $this->position;
}
public function valid()
{
return isset($this->_items[$this->position]);
}
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->_items[] = $value;
} else {
$this->_items[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->_items[$offset]);
}
public function offsetUnset($offset)
{
unset($this->_items[$offset]);
}
public function offsetGet($offset)
{
return $this->offsetExists($offset) ? $this->_items[$offset] : null;
}
}