PHP预定义接口之Iterator用法示例
本文实例讲述了PHP预定义接口之Iterator用法。分享给大家供大家参考,具体如下:
Iterator(迭代器)接口
可在内部迭代自己的外部迭代器或类的接口。
接口摘要
- Iterator extends Traversable {
- /* 方法 */
- abstract public current ( void ) : mixed
- abstract public key ( void ) : scalar
- abstract public next ( void ) : void
- abstract public rewind ( void ) : void
- abstract public valid ( void ) : bool
- }
例:
- <?php
- class myIterator implements Iterator
- {
- private $position = 0;
- private $array = array(
- 'first_element',
- 'second_element',
- 'last_element',
- );
- /**
- * 重置键的位置
- */
- public function rewind(): void
- {
- var_dump(__METHOD__);
- $this->position = 0;
- }
- /**
- * 返回当前元素
- */
- public function current()
- {
- var_dump(__METHOD__);
- return $this->array[$this->position];
- }
- /**
- * 返回当前元素的键
- * @return int
- */
- public function key(): int
- {
- var_dump(__METHOD__);
- return $this->position;
- }
- /**
- * 将键移动到下一位
- */
- public function next(): void
- {
- var_dump(__METHOD__);
- ++$this->position;
- }
- /**
- * 判断键所在位置的元素是否存在
- * @return bool
- */
- public function valid(): bool
- {
- var_dump(__METHOD__);
- return isset($this->array[$this->position]);
- }
- }
- $it = new myIterator;
- foreach ($it as $key => $value) {
- var_dump($key, $value);
- echo "\n";
- }
输出结果:
- string 'myIterator::rewind' (length=18)
- string 'myIterator::valid' (length=17)
- string 'myIterator::current' (length=19)
- string 'myIterator::key' (length=15)
- int 0
- string 'first_element' (length=13)
- string 'myIterator::next' (length=16)
- string 'myIterator::valid' (length=17)
- string 'myIterator::current' (length=19)
- string 'myIterator::key' (length=15)
- int 1
- string 'second_element' (length=14)
- string 'myIterator::next' (length=16)
- string 'myIterator::valid' (length=17)
- string 'myIterator::current' (length=19)
- string 'myIterator::key' (length=15)
- int 2
- string 'last_element' (length=12)
- string 'myIterator::next' (length=16)
- string 'myIterator::valid' (length=17)
由结果可知,当类实现了Iterator接口,实现改类实例数据集的时候首先会将数据集的键重置,然后逐步后移,每次都会进行然后返回当前元素以及当前键。