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"
到此这篇关于php聚合式迭代器的基础知识点及实例代码的文章就介绍到这了,更多相关php聚合式迭代器是什么内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)