了解迭代器之前,先看看Iterator的接口,如下
Iterator extends Traversable {
abstract public mixed current ( void )//返回当前元素
abstract public scalar key( void )//返回当前元素的键
abstract public void next( void )//向前移动到下一个元素
abstract public void rewind( void )//返回到迭代器的第一个元素
abstract public boolean valid ( void )//检查当前位置是否有效
}
实例1
<?php
class MyIterator implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
echo "rewinding<br/>";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "current: $var<br/>";
return $var;
}
public function key() {
$var = key($this->var);
echo "key: $var<br/>";
return $var;
}
public function next() {
$var = next($this->var);
echo "next: $var<br/>";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}<br/>";
return $var;
}
}
$values = array('name','age','sex');
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b<br/>";
echo "<br/>";
echo "<br/>";
echo "<br/>";
}
?>
如下输出
也可以用 IteratorAggregate(聚合式迭代器)来替代实现所有的 Iterator方法。IteratorAggregate 只需要实现一个方法 IteratorAggregate::getIterator(),其应返回一个实现了 Iterator的类的实例。
如下
<?php
class MyIterator implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
echo "rewinding<br/>";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "current: $var<br/>";
return $var;
}
public function key() {
$var = key($this->var);
echo "key: $var<br/>";
return $var;
}
public function next() {
$var = next($this->var);
echo "next: $var<br/>";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}<br/>";
return $var;
}
}
class MyCollection implements IteratorAggregate
{
private $items = array();
private $count = 0;
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]";
echo "<br/>";
echo "<br/>";
echo "<br/>";
echo "<br/>";
}
?>
如下输出
实例2
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
public function __construct() {
$this->position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "<br/>";
}
?>
如下输出