PHP預定義接口——Iterator用法示例
本文實例講述了PHP預定義接口——Iterator用法。分享給大家供大家參考,具體如下:
Iterator(迭代器)接口可在內部迭代自己的外部迭代器或類的接口。
接口摘要Iterator extends Traversable { /* 方法 */ abstract public current ( void ) : mixed abstract public key ( void ) : scalar abstract public next ( void ) : void abstract public rewind ( void ) : void abstract public valid ( void ) : bool}例:
<?phpclass myIterator implements Iterator{ private $position = 0; private $array = array( ’first_element’, ’second_element’, ’last_element’, ); /** * 重置鍵的位置 */ public function rewind(): void { var_dump(__METHOD__); $this->position = 0; } /** * 返回當前元素 */ public function current() { var_dump(__METHOD__); return $this->array[$this->position]; } /** * 返回當前元素的鍵 * @return int */ public function key(): int { var_dump(__METHOD__); return $this->position; } /** * 將鍵移動到下一位 */ public function next(): void { var_dump(__METHOD__); ++$this->position; } /** * 判斷鍵所在位置的元素是否存在 * @return bool */ public function valid(): bool { var_dump(__METHOD__); return isset($this->array[$this->position]); }}$it = new myIterator;foreach ($it as $key => $value) { var_dump($key, $value); echo 'n';}
輸出結果:
string ’myIterator::rewind’ (length=18)string ’myIterator::valid’ (length=17)string ’myIterator::current’ (length=19)string ’myIterator::key’ (length=15)int 0string ’first_element’ (length=13)string ’myIterator::next’ (length=16)string ’myIterator::valid’ (length=17)string ’myIterator::current’ (length=19)string ’myIterator::key’ (length=15)int 1string ’second_element’ (length=14)string ’myIterator::next’ (length=16)string ’myIterator::valid’ (length=17)string ’myIterator::current’ (length=19)string ’myIterator::key’ (length=15)int 2string ’last_element’ (length=12)string ’myIterator::next’ (length=16)string ’myIterator::valid’ (length=17)
由結果可知,當類實現(xiàn)了Iterator接口,實現(xiàn)改類實例數(shù)據(jù)集的時候首先會將數(shù)據(jù)集的鍵重置,然后逐步后移,每次都會進行然后返回當前元素以及當前鍵。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章:
1. ASP常用日期格式化函數(shù) FormatDate()2. Python 操作 MySQL數(shù)據(jù)庫3. Python數(shù)據(jù)相關系數(shù)矩陣和熱力圖輕松實現(xiàn)教程4. 開發(fā)效率翻倍的Web API使用技巧5. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動輸入功能實現(xiàn)代碼8. 什么是Python變量作用域9. vue使用moment如何將時間戳轉為標準日期時間格式10. python 如何在 Matplotlib 中繪制垂直線
