迭代器(Iterator)模式,在一个很常见的过程上提供了一个抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代。
迭代有几种不同的具体执行方法:在数组属性,集合对象,数组,甚至一个查询结果集之上迭代。
在PHP官方手册中可以找到完整的SPL迭代器列表。得益于对PHP的强力支持,使用迭代器模式的大部分工作都包括在标准实现中,下面的代码示例就利用了标准Iterator的功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<?php
//定义一个类,实现了Iterator的方法
class
testIterator
implements
Iterator {
private
$_content
;
private
$_index
= 0;
//构造函数
public
function
__construct(
array
$content
) {
$this
->_content =
$content
;
}
//返回到迭代器的第一个元素
public
function
rewind
() {
$this
->_index = 0;
}
//检查当前位置是否有效
public
function
valid() {
return
isset(
$this
->_content[
$this
->_index]);
}
//返回当前元素
public
function
current() {
return
$this
->_content[
$this
->_index];
}
//返回当前元素的键
public
function
key() {
return
$this
->_index;
}
//向前移动到下一个元素
public
function
next() {
$this
->_index++;
}
}
//定义数组,生成类时使用
$arrString
=
array
(
'jane'
,
'apple'
,
'orange'
,
'pear'
);
$testIterator
=
new
testIterator(
$arrString
);
//开始迭代对象
foreach
(
$testIterator
as
$key
=>
$val
) {
echo
$key
.
'=>'
.
$val
.
'<br>'
;
}
|
运行可以看到如下结果:
1
2
3
4
|
0=>jane
1=>apple
2=>orange
3=>pear
|
如果有兴趣,可以在每一个函数里面开始处加上“var_dump(__METHOD__);”,这样就可以看到每个函数的调用顺序了,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
string(25)
"testIterator::__construct"
string(20)
"testIterator::rewind"
string(19)
"testIterator::valid"
string(21)
"testIterator::current"
string(17)
"testIterator::key"
0=>jane
string(18)
"testIterator::next"
string(19)
"testIterator::valid"
string(21)
"testIterator::current"
string(17)
"testIterator::key"
1=>apple
string(18)
"testIterator::next"
string(19)
"testIterator::valid"
string(21)
"testIterator::current"
string(17)
"testIterator::key"
2=>orange
string(18)
"testIterator::next"
string(19)
"testIterator::valid"
string(21)
"testIterator::current"
string(17)
"testIterator::key"
3=>pear
string(18)
"testIterator::next"
string(19)
"testIterator::valid"
|
本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1344851
,如需转载请自行联系原作者