一、概述
本篇文章主要介绍通过Iterator迭代器实现遍历数组对象的属性数组值。
二、代码
class myIterator implements Iterator
{
private $position = 0;
private $array = ["firstElement", "secondElement", "lastElement",];
public function __construct() {
$this->position = 0;
}
// 当开始一个 foreach 循环时,这是第一个被调用的方法
function rewind() {
$this->position = 0;
}
// 返回当前元素值
function current() {
return $this->array[$this->position];
}
// 返回当前元素的键
function key() {
return $this->position;
}
// 此方法在 foreach 循环之后被调用,使得继续循环,不然会一直阻断在current和key
function next() {
++$this->position;
}
// 此方法在 每次要开始循环的时候判断一下
function valid() {
return isset($this->array[$this->position]);
}
}
$it = new myIterator;
// 执行顺序:rewind->valid->current->key->next->valid->current->key->...->valid->结束
// 相当于对数组["firstElement", "secondElement", "lastElement",]进行迭代
foreach ($it as $key => $value) {
echo $key, $value, "<br />";
}