SPL迭代器接口(三)—SeekableIterator Interface

  SeekableIterator Interface: Iterator接口的扩展,实现该接口允许通过键值进行查找。

  SeekableIterator接口继承自Iterator接口。实现SeekableIterator接口,除了需实现Iterator的5个方法以外,还要求实现seek()方法,参数是元素的下标。

  SeekableIterator接口通过要求实现seek方法,通过实现seek方法提供了按下标索引元素的能力。

  代码示例:

‹?php
//自定义数组容器实现迭代器接口
class MySeekableIterator implements SeekableIterator
{
    protected $data = array('唐朝','宋朝','元朝');  //存放数据
    protected $index ;         //存放当前指针
    //按下标返回元素
    public function seek($key){
        return $this->data[$key];
    }
    //返回当前指针指向数据
    public function current()
    {   
        return $this->data[$this->index];
    }
    //指针+1
    public function next()
    {   
        $this->index ++;
    }
    //验证指针是否越界
    public function valid()
    {   
        return $this->index ‹ count($this->data);
    }
    //重置指针
    public function rewind()
    {   
        $this->index = 0;
    }
    //返回当前指针
    public function key()
    {   
        return $this->index;
    }
}

//实例化一个迭代器
$container = new MySeekableIterator();
//遍历数组容器
foreach($container as $key =>$dynasty){
    echo '如果有时光机,我想去'.$dynasty.PHP_EOL;
}
//按下标返回元素
echo '我最想去的是'.$container->seek(1);

  运行结果:

来源:慕课手记 https://www.imooc.com/article/17898

转载请注明出处:https://www.onexin.net/spl-seekableiterator-interface/

相关文章:

1、SPL迭代器接口(六)—RecursiveIterator Interface
https://www.onexin.net/spl-recursiveiterator-interface/

2、SPL迭代器接口(五)—OuterIterator Interface
https://www.onexin.net/spl-outeriterator-interface/

3、SPL迭代器接口(四)—IteratorAggregate Interface
https://www.onexin.net/spl-iteratoraggregate-interface/

4、SPL迭代器接口(二)—Iterator Interface
https://www.onexin.net/spl-iterator-interface/

5、SPL迭代器接口(一)—Traversable Interface
https://www.onexin.net/spl-traversable-interface/

Leave a Reply