温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-16 21:29:51 来源:网络 阅读:450 作者:shayang88 栏目:web开发

迭代器(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"


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI