PHP聚合式迭代器接口IteratorAggregate用法分析
本文實例講述了PHP聚合式迭代器接口IteratorAggregate用法。分享給大家供大家參考,具體如下:
PHP IteratorAggregate又叫聚合式迭代器,它提供了創(chuàng)建外部迭代器的接口,接口摘要如下:
IteratorAggregate extends Traversable {
abstract public Traversable getIterator ( void )
}
實現(xiàn)getIterator方法時必須返回一個實現(xiàn)了Iterator接口的類的實例。
例子說明:
<?php
/**
* 利用聚合式迭代器,并返回一個實現(xiàn)了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迭代器會把對象或數(shù)組封裝為一個可以通過foreach來操作的類,具體可參考SPL 迭代器相關介紹,感興趣的朋友可參考本站http://www.dhdzp.com/article/43074.htm。
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP中利用substr_replace將指定兩位置之間的字符替換為*號
PHP的substr_replace將指定兩位置之間的字符替換為*號的代碼,需要的朋友可以參考下。2011-01-01
在WordPress中獲取數(shù)據(jù)庫字段內(nèi)容和添加主題設置菜單
這篇文章主要介紹了在WordPress中獲取數(shù)據(jù)庫字段內(nèi)容和添加主題設置菜單的方法,分別講解了get_option()函數(shù)和add_theme_page()函數(shù)的用法,需要的朋友可以參考下2016-01-01
ubuntu 編譯安裝php 5.3.3+memcache的方法
ubuntu 編譯安裝php 5.3.3+memcache的方法,需要的朋友可以參考下。2010-08-08
PHP多維數(shù)組轉一維數(shù)組的簡單實現(xiàn)方法
這篇文章主要介紹了PHP多維數(shù)組轉一維數(shù)組的簡單實現(xiàn)方法,涉及PHP遞歸操作技巧,簡單實用,需要的朋友可以參考下2015-12-12
Nginx環(huán)境下PHP flush失效的解決方法
最近在工作中發(fā)現(xiàn)了一個問題,PHP的flush居然失效了,從網(wǎng)上找了一些資料,發(fā)現(xiàn)是Nginx的原因,所以這篇文章就給大家介紹了問題與解決辦法,有需要的朋友們下面來一起看看吧。2016-10-10
PHP實現(xiàn)動態(tài)創(chuàng)建XML文檔的方法
這篇文章主要介紹了PHP實現(xiàn)動態(tài)創(chuàng)建XML文檔的方法,結合實例形式分析了php針對xml格式數(shù)據(jù)的構建及文件讀寫相關操作技巧,需要的朋友可以參考下2018-03-03

