spl应用场景 -- IteratorIterator迭代器

来源:互联网 发布:单桂敏淘宝店铺 编辑:程序博客网 时间:2024/06/16 12:20

spl应用场景 – IteratorIterator迭代器

* 1.介绍*
改迭代器接口,主要可以 “迭代” 迭代器, 例如
ArrayIterator
类结构如下:

IteratorIteratorimplements OuterIterator {/* 方法 */public __construct ( Traversable $iterator )public mixed current ( void )public Traversable getInnerIterator ( void )public scalar key ( void )public void next ( void )public void rewind ( void )public bool valid ( void ) }

2.参考示例 枚举

<?phpclass Enumerator extends IteratorIterator {        /**     * Initial value for enumerator     * @param int      */     protected $start = 0;    /**     * @param int     */     protected $key = 0;    /**     * @param Traversable $iterator     * @param scalar $start     */     public function __construct(Traversable $iterator, $start = 0)     {         parent::__construct($iterator);        $this->start = $start;        $this->key = $this->start;     }    public function key()     {         return $this->key;     }    public function next()     {         ++$this->key;        parent::next();     }    public function rewind()     {         $this->key = $this->start;        parent::rewind();     }}$enumerator = new Enumerator(        new ArrayIterator(['php', 'java', 'python']), 7000 );print_r(iterator_to_array($enumerator));/* 输出 *    array(3) {            7000 => 'php',            7001 => 'java',            7002 => 'python'      } */?>

总结:
1. new Enumerator()时候,传入是ArrayIterator 迭代器,其构造函数第一个参数类型是Traversable,主要判断迭代器是否支持foreach
2.IteratorIterator是众多迭代器继承的

0 0
原创粉丝点击