php聚合式迭代器的基础知识点及实例代码
发布:smiling 来源: PHP粉丝网 添加日期:2022-05-06 09:29:43 浏览: 评论:0
在本篇文章里小编给大家整理的是一篇关于php聚合式迭代器的基础知识点及实例代码,有兴趣的朋友们可以学习参考下。
说明
1、实现其他迭代器功能的接口,相当于在其他迭代器上安装一个外壳,只有一种方法。
2、聚合迭代器可以与许多迭代器结合,实现更高效的迭代。
实例
- class MainIterator implements Iterator
 - {
 - private $var = array();
 - public function __construct($array) //构造函数, 初始化对象数组
 - {
 - if (is_array($array)) {
 - $this->var = $array;
 - }
 - }
 - public function rewind() {
 - echo "rewinding\n";
 - reset($this->var); //将数组的内部指针指向第一个单元
 - }
 - public function current() {
 - $var = current($this->var); // 返回数组中的当前值
 - echo "current: $var\n";
 - return $var;
 - }
 - public function key() {
 - $var = key($this->var); //返回数组中内部指针指向的当前单元的键名
 - echo "key: $var\n";
 - return $var;
 - }
 - public function next() {
 - $var = next($this->var); //返回数组内部指针指向的下一个单元的值
 - echo "next: $var\n";
 - return $var;
 - }
 - public function valid() {
 - return !is_null(key($this->var); //判断当前单元的键是否为空
 - }
 - }
 
内容扩展:
- <?php
 - class myData implements IteratorAggregate {
 - public $property1 = "Public property one";
 - public $property2 = "Public property two";
 - public $property3 = "Public property three";
 - public function __construct() {
 - $this->property4 = "last property";
 - }
 - public function getIterator() {
 - return new ArrayIterator($this);
 - }
 - }
 - $obj = new myData;
 - foreach($obj as $key => $value) {
 - var_dump($key, $value);
 - echo "\n";
 - }
 - ?>
 
以上例程的输出类似于:
- string(9) "property1"
 - string(19) "Public property one"
 - string(9) "property2"
 - string(19) "Public property two"
 - string(9) "property3"
 - string(21) "Public property three"
 - string(9) "property4"
 - string(13) "last property"
 
Tags: php聚合式迭代器
- 上一篇:php桥接模式的实例用法及代码分析
 - 下一篇:最后一页
 
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
 - PHP新手上路(一)(7)
 - 惹恼程序员的十件事(5)
 - PHP邮件发送例子,已测试成功(5)
 - 致初学者:PHP比ASP优秀的七个理由(4)
 - PHP会被淘汰吗?(4)
 - PHP新手上路(四)(4)
 - 如何去学习PHP?(2)
 - 简单入门级php分页代码(2)
 - php中邮箱email 电话等格式的验证(2)
 
