background image

foreach

(

$it

 

as

 

$key

 => 

$value

) {

 echo

 '输出键值:';

    

var_dump(

$key

$value

);

 

//echo $key;

    echo

 "\n";

}
 
 
程序运行输出:
代码如下

:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
输出键值:

int(0)

string(13) "first_element"
 
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
输出键值:

int(1)

string(14) "second_element"
 
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
输出键值:

int(2)

string(12) "last_element"
 
string(16) "myIterator::next"
string(17) "myIterator::valid"
 
 
一般的迭代器内部需要下面的方法:
Iterator::current — Return the current element 返回当前元素
Iterator::key — Return the key of the current element 返回当前元素的键
Iterator::next — Move forward to next element 移向下一个元素
Iterator::

rewind

 — 

Rewind

 the Iterator to the first element 重新回到第一个元素

Iterator::valid — Checks 

if

 current position is valid 检查当前位置的有效性

如果不是很清楚迭代器的内容工作流程,可以查看下面的迭代器对数组的遍历过程:
代码如下

:

/**