PHP迭代器和迭代的實現(xiàn)與使用方法分析
本文實例講述了PHP迭代器和迭代的實現(xiàn)與使用方法。分享給大家供大家參考,具體如下:
PHP的面向對象引擎提供了一個非常聰明的特性,就是,可以使用foreach()
方法通過循環(huán)方式取出一個對象的所有屬性,就像數(shù)組方式一樣,代碼如下:
class Myclass{ public $a = 'php'; public $b = 'onethink'; public $c = 'thinkphp'; } $myclass = new Myclass(); //用foreach()將對象的屬性循環(huán)出來 foreach($myclass as $key.'=>'.$val){ echo '$'.$key.' = '.$val."<br/>"; } /*返回 $a = php $b = onethink $c = thinkphp */
如果需要實現(xiàn)更加復雜的行為,可以通過一個iterator
(迭代器)來實現(xiàn)
//迭代器接口 interface MyIterator{ //函數(shù)將內(nèi)部指針設置回數(shù)據(jù)開始處 function rewind(); //函數(shù)將判斷數(shù)據(jù)指針的當前位置是否還存在更多數(shù)據(jù) function valid(); //函數(shù)將返回數(shù)據(jù)指針的值 function key(); //函數(shù)將返回將返回當前數(shù)據(jù)指針的值 function value(); //函數(shù)在數(shù)據(jù)中移動數(shù)據(jù)指針的位置 function next(); } //迭代器類 class ObjectIterator implements MyIterator{ private $obj;//對象 private $count;//數(shù)據(jù)元素的數(shù)量 private $current;//當前指針 function __construct($obj){ $this->obj = $obj; $this->count = count($this->obj->data); } function rewind(){ $this->current = 0; } function valid(){ return $this->current < $this->count; } function key(){ return $this->current; } function value(){ return $this->obj->data[$this->current]; } function next(){ $this->current++; } } interface MyAggregate{ //獲取迭代器 function getIterator(); } class MyObject implements MyAggregate{ public $data = array(); function __construct($in){ $this->data = $in; } function getIterator(){ return new ObjectIterator($this); } } //迭代器的用法 $arr = array(2,4,6,8,10); $myobject = new MyObject($arr); $myiterator = $myobject->getIterator(); for($myiterator->rewind();$myiterator->valid();$myiterator->next()){ $key = $myiterator->key(); $value = $myiterator->value(); echo $key.'=>'.$value; echo "<br/>"; } /*返回 0=>2 1=>4 2=>6 3=>8 4=>10 */
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
- PHP設計模式之迭代器模式Iterator實例分析【對象行為型】
- php設計模式之迭代器模式實例分析【星際爭霸游戲案例】
- PHP設計模式之迭代器(Iterator)模式入門與應用詳解
- PHP迭代器和生成器用法實例分析
- php和C#的yield迭代器實現(xiàn)方法對比分析
- PHP設計模式之PHP迭代器模式講解
- PHP基于SPL實現(xiàn)的迭代器模式示例
- PHP聚合式迭代器接口IteratorAggregate用法分析
- PHP迭代器接口Iterator用法分析
- PHP迭代器的內(nèi)部執(zhí)行過程詳解
- PHP設計模式之迭代器模式的深入解析
- PHP中迭代器的簡單實現(xiàn)及Yii框架中的迭代器實現(xiàn)方法示例
相關文章
PHP超級全局變量【$GLOBALS,$_SERVER,$_REQUEST等】用法實例分析
這篇文章主要介紹了PHP超級全局變量用法,結合實例形式分析了PHP中$GLOBALS,$_SERVER,$_REQUEST等超級全局變量相關概念、功能、使用方法及操作注意事項,需要的朋友可以參考下2019-12-12非常好用的兩個PHP函數(shù) serialize()和unserialize()
使用serialize()函數(shù)和unserialize()函數(shù),這兩個函數(shù)的用法真是絕配,一個是進行序列化存儲,另一個則是進行序列化恢復,方便極了2012-02-02