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