這篇文章給大家分享的是PHP的聚合式迭代器的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,文中示例代碼介紹的非常詳細(xì),感興趣的朋友接下來(lái)一起跟隨小編看看吧。
說(shuō)明
1、實(shí)現(xiàn)其他迭代器功能的接口,相當(dāng)于在其他迭代器上安裝一個(gè)外殼,只有一種方法。
2、聚合迭代器可以與許多迭代器結(jié)合,實(shí)現(xiàn)更高效的迭代。
實(shí)例
class MainIterator implements Iterator { private $var = array(); public function __construct($array) //構(gòu)造函數(shù), 初始化對(duì)象數(shù)組 { if (is_array($array)) { $this->var = $array; } } public function rewind() { echo "rewinding\n"; reset($this->var); //將數(shù)組的內(nèi)部指針指向第一個(gè)單元 } public function current() { $var = current($this->var); // 返回?cái)?shù)組中的當(dāng)前值 echo "current: $var\n"; return $var; } public function key() { $var = key($this->var); //返回?cái)?shù)組中內(nèi)部指針指向的當(dāng)前單元的鍵名 echo "key: $var\n"; return $var; } public function next() { $var = next($this->var); //返回?cái)?shù)組內(nèi)部指針指向的下一個(gè)單元的值 echo "next: $var\n"; return $var; } public function valid() { return !is_null(key($this->var); //判斷當(dāng)前單元的鍵是否為空 } }
內(nèi)容擴(kuò)展:
<?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的聚合式迭代器的內(nèi)容就介紹到這,上述示例對(duì)大家學(xué)習(xí)PHP的聚合式迭代器的使用有一定的借鑒價(jià)值,感興趣的朋友可以參考,希望能對(duì)大家有幫助,想要了解更多大家可以關(guān)注其它的相關(guān)文章。