久久福利_99r_国产日韩在线视频_直接看av的网站_中文欧美日韩_久久一

您的位置:首頁技術文章
文章詳情頁

常用設計模式之迭代器模式及其PHP實現(xiàn)(Yii框架)

瀏覽:7日期:2022-09-13 09:01:45

迭代器模式是一種行為型模式,它是一種最簡單也最常見的設計模式。它可以讓使用者透過特定的接口巡訪容器中的每一個元素而不用了解底層的實際操作。

適用性在希望利用語言本身的遍歷函數(shù)便利自定義結構時,例如PHP中的foreach函數(shù)類圖

常用設計模式之迭代器模式及其PHP實現(xiàn)(Yii框架)

PHP實例

<?phpclass sample implements Iterator { private $_items ; public function __construct(&$data) {$this->_items = $data; } public function current() {return current($this->_items); } public function next() {next($this->_items); } public function key() {return key($this->_items); } public function rewind() {reset($this->_items); } public function valid() { return ($this->current() !== FALSE); }} // client$data = array(1, 2, 3, 4, 5);$sa = new sample($data);foreach ($sa AS $key => $row) { echo $key, ’ ’, $row, ’<br />’;}?>在Yii框架中的實現(xiàn):

在Yii框架中的我們可以看到其迭代器的實現(xiàn),在collections目錄下的CMapIterator.php文件中,其實現(xiàn)如下:

class CMapIterator implements Iterator {/*** @var array the data to be iterated through*/ private $_d;/*** @var array list of keys in the map*/ private $_keys;/*** @var mixed current key*/ private $_key; /*** Constructor.* @param array the data to be iterated through*/ public function __construct(&$data) {$this->_d=&$data;$this->_keys=array_keys($data); } /*** Rewinds internal array pointer.* This method is required by the interface Iterator.*/ public function rewind() { $this->_key=reset($this->_keys); } /*** Returns the key of the current array element.* This method is required by the interface Iterator.* @return mixed the key of the current array element*/ public function key() {return $this->_key; } /*** Returns the current array element.* This method is required by the interface Iterator.* @return mixed the current array element*/ public function current() {return $this->_d[$this->_key]; } /*** Moves the internal pointer to the next array element.* This method is required by the interface Iterator.*/ public function next() {$this->_key=next($this->_keys); } /*** Returns whether there is an element at current position.* This method is required by the interface Iterator.* @return boolean*/ public function valid() {return $this->_key!==false; }} $data = array(’s1’ => 11, ’s2’ => 22, ’s3’ => 33);$it = new CMapIterator($data);foreach ($it as $row) { echo $row, ’<br />’;}

這與之前的簡單實現(xiàn)相比,其位置的變化是通過控制key來實現(xiàn)的,這種實現(xiàn)的作用是為了避免false作為數(shù)組值時無法迭代。

標簽: PHP
相關文章:
主站蜘蛛池模板: 国产日韩免费视频 | av网站推荐 | 精品视频免费观看 | 精品免费视频 | 色婷婷综合久久久中文字幕 | 久久精品亚洲精品国产欧美 | 国产精品不卡视频 | 欧美日韩一区二区视频在线观看 | 91精品国产综合久久久久久丝袜 | 久久三级视频 | 欧美日韩一区二区三区不卡视频 | 国产成人精品免高潮在线观看 | 99久久久久久久久 | 欧美日韩在线视频一区二区 | 国产欧美综合在线 | 91午夜精品一区二区三区 | 高清av网址 | 欧美国产视频 | 久久综合久久久 | 欧美日本久久 | 国产高清一级毛片在线不卡 | 国产综合亚洲精品一区二 | 爱爱视频网站 | 日本a v在线播放 | 人人射人人舔 | 久久久精品国产 | 思九九爱九九 | 免费国产视频 | 中文字幕一区在线观看视频 | 国产高清精品一区二区三区 | 久久天堂热| 26uuu成人免费毛片 | 免费视频一区 | 国产视频二区 | 精品日韩欧美一区二区在线播放 | 国产精品视频一区二区三区 | 超黄视频在线观看 | 色吊丝在线永久观看最新版本 | 日本不卡高字幕在线2019 | 欧美一级在线 | 亚洲一区在线日韩在线深爱 |