PHP Iterator(迭代器) 遍历值 作者: Chuwen 时间: 2020-12-04 分类: PHP # 有这么一个迭代器 ```php class myIterator implements Iterator { private $index = 0; private $data = ''; public function __construct($data) { $this->index = 0; $this->data = $data; } function rewind() { $this->index = 0; } function current() { return $this->data[$this->index]; } function key() { return $this->index; } function next() { ++$this->index; } function valid() { return isset($this->data[$this->index]); } } $it = new myIterator(array( "hello", "php", "iterator", )); ``` # 遍历取值 ## 1. while 循环♻️取值 ```php valid()){ echo "key: {$it->key()} , value: {$it->current()}".PHP_EOL; $it->next();//指向下一项 } ``` ## 2. foreach 取值 > 我们通过 `foreach` 遍历 `$it` 时,PHP 会自己依次调用: > > `rewind()` 重置到第一个元素 > `valid()` 检查当前位置是否有效 > `current()` 返回当前元素 > `key()` 返回当前元素的键 > `next()` 指向下一个元素 ```php foreach($it as $key => $value) { echo "$key : $value"; } ``` --- 部分摘抄自:https://segmentfault.com/a/1190000016475883 标签: PHP, Iterator, 迭代器