当前位置:首页 > PHP教程 > php高级应用 > 列表

php聚合式迭代器的基础知识点及实例代码

发布:smiling 来源: PHP粉丝网  添加日期:2022-05-06 09:29:43 浏览: 评论:0 

在本篇文章里小编给大家整理的是一篇关于php聚合式迭代器的基础知识点及实例代码,有兴趣的朋友们可以学习参考下。

说明

1、实现其他迭代器功能的接口,相当于在其他迭代器上安装一个外壳,只有一种方法。

2、聚合迭代器可以与许多迭代器结合,实现更高效的迭代。

实例

  1. class MainIterator implements Iterator 
  2. { 
  3.     private $var = array(); 
  4.     public function __construct($array)    //构造函数, 初始化对象数组 
  5.     { 
  6.         if (is_array($array)) { 
  7.         $this->var = $array; 
  8.         } 
  9.     } 
  10.    
  11.     public function rewind() {    
  12.         echo "rewinding\n"; 
  13.         reset($this->var);    //将数组的内部指针指向第一个单元 
  14.     } 
  15.    
  16.     public function current() { 
  17.         $var = current($this->var);    // 返回数组中的当前值 
  18.         echo "current: $var\n"; 
  19.         return $var; 
  20.     } 
  21.    
  22.     public function key() { 
  23.         $var = key($this->var);       //返回数组中内部指针指向的当前单元的键名 
  24.         echo "key: $var\n"; 
  25.         return $var; 
  26.     } 
  27.    
  28.     public function next() { 
  29.         $var = next($this->var);     //返回数组内部指针指向的下一个单元的值 
  30.         echo "next: $var\n"; 
  31.         return $var; 
  32.     } 
  33.    
  34.     public function valid() { 
  35.     return !is_null(key($this->var); //判断当前单元的键是否为空 
  36.     } 
  37. } 

内容扩展:

  1. <?php 
  2. class myData implements IteratorAggregate { 
  3.     public $property1 = "Public property one"; 
  4.     public $property2 = "Public property two"; 
  5.     public $property3 = "Public property three"; 
  6.  
  7.     public function __construct() { 
  8.         $this->property4 = "last property"; 
  9.     } 
  10.  
  11.     public function getIterator() { 
  12.         return new ArrayIterator($this); 
  13.     } 
  14. } 
  15.  
  16. $obj = new myData; 
  17.  
  18. foreach($obj as $key => $value) { 
  19.     var_dump($key, $value); 
  20.     echo "\n"; 
  21. } 
  22. ?> 

以上例程的输出类似于:

  1. string(9) "property1" 
  2. string(19) "Public property one" 
  3.  
  4. string(9) "property2" 
  5. string(19) "Public property two" 
  6.  
  7. string(9) "property3" 
  8. string(21) "Public property three" 
  9.  
  10. string(9) "property4" 
  11. string(13) "last property"

Tags: php聚合式迭代器

分享到: