您的位置:首页 > 编程语言 > PHP开发

PHP设计模式(6)迭代器模式

2013-12-25 21:28 639 查看
迭代器(Iterator)模式,在一个很常见的过程上提供了一个抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代。
迭代有几种不同的具体执行方法:在数组属性,集合对象,数组,甚至一个查询结果集之上迭代。
在PHP官方手册中可以找到完整的SPL迭代器列表。得益于对PHP的强力支持,使用迭代器模式的大部分工作都包括在标准实现中,下面的代码示例就利用了标准Iterator的功能。
<?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>';
}
运行可以看到如下结果:
0=>jane
1=>apple
2=>orange
3=>pear
如果有兴趣,可以在每一个函数里面开始处加上“var_dump(__METHOD__);”,这样就可以看到每个函数的调用顺序了,如下:
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"


本文出自 “phper-每天一点点~” 博客,请务必保留此出处http://janephp.blog.51cto.com/4439680/1344851
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: