說明
1、實現(xiàn)其他迭代器功能的接口,相當(dāng)于在其他迭代器上安裝一個外殼,只有一種方法。
2、聚合迭代器可以與許多迭代器結(jié)合,實現(xiàn)更高效的迭代。
實例
class MainIterator implements Iterator
{
private $var = array();
public function __construct($array) //構(gòu)造函數(shù), 初始化對象數(shù)組
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind() {
echo "rewinding\n";
reset($this->var); //將數(shù)組的內(nèi)部指針指向第一個單元
}
public function current() {
$var = current($this->var); // 返回數(shù)組中的當(dāng)前值
echo "current: $var\n";
return $var;
}
public function key() {
$var = key($this->var); //返回數(shù)組中內(nèi)部指針指向的當(dāng)前單元的鍵名
echo "key: $var\n";
return $var;
}
public function next() {
$var = next($this->var); //返回數(shù)組內(nèi)部指針指向的下一個單元的值
echo "next: $var\n";
return $var;
}
public function valid() {
return !is_null(key($this->var); //判斷當(dāng)前單元的鍵是否為空
}
}
內(nèi)容擴展:
?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"
到此這篇關(guān)于php聚合式迭代器的基礎(chǔ)知識點及實例代碼的文章就介紹到這了,更多相關(guān)php聚合式迭代器是什么內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- PHP聚合式迭代器接口IteratorAggregate用法分析