迭代:是指反复执行一个过程,每执行一次叫做迭代一次。比如普通的遍历便是迭代:

接口方法

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 bool valid ( void )
}

实现接口

class IteratorDemo implements Iterator
{
    private $index = 0;

    private $data = ['first', 'second', 'third', 'four'];

    /**
     * 返回当前元素
     */
    public function current()
    {
        echo "current <br />" ;
        return $this->data[$this->index];
    }

    /**
     * 向前移动到下一个元素
     */
    public function next()
    {
        echo "next <br />" ;
        ++$this->index;
    }
    /**
     *  返回当前元素的键
     */
    public function key()
    {
        echo "key <br />" ;
        return $this->index;
    }

    /**
     * 检查当前位置是否有效
     */
    public function valid()
    {
        echo "valid <br />" ;
        return isset($this->data[$this->index]);
    }

    /**
     * 移动到迭代器的第一个元素
     */
    public function rewind()
    {
        echo "rewind <br />" ;
        $this->index = 0;
    }
}

运行

$obj = new IteratorDemo();

foreach($obj as $key => $value) {
    echo $key." => ".$value;

    echo "<br /><br />";
}

输出结果

rewind 
valid 
current 
key 
0 => first

next 
valid 
current 
key 
1 => second

next 
valid 
current 
key 
2 => third

next 
valid 
current 
key 
3 => four

next 
valid

通过运行的结果,我们可以清晰的看到迭代器的调用顺序。