迭代器(Iterator)模式,在一個很常見的過程上提供了一個抽象:位于對象圖不明部分的一組對象(或標量)集合上的迭代。
創(chuàng)新互聯(lián)是一家專注于網站設計、成都網站制作與策劃設計,鄰水網站建設哪家好?創(chuàng)新互聯(lián)做網站,專注于網站建設十余年,網設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:鄰水等地區(qū)。鄰水做網站價格咨詢:13518219792
迭代有幾種不同的具體執(zhí)行方法:在數(shù)組屬性,集合對象,數(shù)組,甚至一個查詢結果集之上迭代。
在PHP官方手冊中可以找到完整的SPL迭代器列表。得益于對PHP的強力支持,使用迭代器模式的大部分工作都包括在標準實現(xiàn)中,下面的代碼示例就利用了標準Iterator的功能。
<?php //定義一個類,實現(xiàn)了Iterator的方法 class testIterator implements Iterator { private $_content; private $_index = 0; //構造函數(shù) public function __construct(array $content) { $this->_content = $content; } //返回到迭代器的第一個元素 public function rewind() { $this->_index = 0; } //檢查當前位置是否有效 public function valid() { return isset($this->_content[$this->_index]); } //返回當前元素 public function current() { return $this->_content[$this->_index]; } //返回當前元素的鍵 public function key() { return $this->_index; } //向前移動到下一個元素 public function next() { $this->_index++; } } //定義數(shù)組,生成類時使用 $arrString = array('jane','apple','orange','pear'); $testIterator = new testIterator($arrString); //開始迭代對象 foreach ( $testIterator as $key => $val ) { echo $key . '=>' . $val . '<br>'; }
運行可以看到如下結果:
0=>jane 1=>apple 2=>orange 3=>pear
如果有興趣,可以在每一個函數(shù)里面開始處加上“var_dump(__METHOD__);”,這樣就可以看到每個函數(shù)的調用順序了,如下:
string(25) "testIterator::__construct" string(20) "testIterator::rewind" string(19) "testIterator::valid" string(21) "testIterator::current" string(17) "testIterator::key" 0=>jane string(18) "testIterator::next" string(19) "testIterator::valid" string(21) "testIterator::current" string(17) "testIterator::key" 1=>apple string(18) "testIterator::next" string(19) "testIterator::valid" string(21) "testIterator::current" string(17) "testIterator::key" 2=>orange string(18) "testIterator::next" string(19) "testIterator::valid" string(21) "testIterator::current" string(17) "testIterator::key" 3=>pear string(18) "testIterator::next" string(19) "testIterator::valid"
分享文章:PHP設計模式(6)迭代器模式
轉載源于:http://www.rwnh.cn/article16/jdcggg.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網站制作、商城網站、移動網站建設、搜索引擎優(yōu)化、品牌網站設計、品牌網站制作
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)