本文實例講述了PHP聚合式迭代器接口IteratorAggregate用法。分享給大家供大家參考,具體如下:
PHP IteratorAggregate又叫聚合式迭代器,它提供了創建外部迭代器的接口,接口摘要如下:
IteratorAggregate extends Traversable { abstract public Traversable getIterator ( void )}
實現getIterator方法時必須返回一個實現了Iterator接口的類的實例。
例子說明:
<?php/** * 利用聚合式迭代器,并返回一個實現了Iterator接口的類的實例 * * @author 瘋狂老司機 */class myData implements IteratorAggregate { public $one = "Public property one"; public $two = "Public property two"; public $three = "Public property three"; public function __construct() { $this->last = "last property"; } public function getIterator() { return new ArrayIterator($this); }}$obj = new myData;foreach($obj as $key => $value) { var_dump($key, $value); echo '<br>';// Linux:echo "/n";}?>
以上例子輸出:
string 'one' (length=3)string 'Public property one' (length=19)string 'two' (length=3)string 'Public property two' (length=19)string 'three' (length=5)string 'Public property three' (length=21)string 'last' (length=4)string 'last property' (length=13)
ArrayIterator迭代器會把對象或數組封裝為一個可以通過foreach來操作的類
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選