国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

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

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

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

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

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

常用設計模式之迭代器模式及其PHP實現(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框架中的實現:

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

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 />’;}

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

標簽: PHP
相關文章:
主站蜘蛛池模板: 一级欧美毛片成人 | 99热在线免费 | 狠狠色丁香婷婷综合小时婷婷 | 亚欧在线 | 美女黄页网站免费进入 | 欧美一级aⅴ毛片 | 日韩毛片久久91 | 免费一级美国片在线观看 | 欧美成人免费夜夜黄啪啪 | 美女网站视频黄色 | 欧美一级毛片高清免费观看 | 日韩中文字幕在线观看 | 久久一本色系列综合色 | 国产高清无专砖区2021 | 亚洲精品久久久久影 | 日韩亚洲一区中文字幕在线 | 国产高清亚洲精品26u | 日韩专区亚洲精品欧美专区 | 亚洲欧美国产精品专区久久 | 欧美精品久久久久久久久大尺度 | 久久污| 国产一级精品高清一级毛片 | 久久久91精品国产一区二区 | 成人精品一区二区不卡视频 | 国产成人tv在线观看 | 超清首页 国产 亚洲 丝袜 | 免费在线精品视频 | 综合 欧美 国产 视频二区 | 美女张开腿让我 | a免费网站 | 欧美一级毛片一免费 | 高清国产一级精品毛片基地 | bt天堂国产亚洲欧美在线 | 国产成人精品亚洲 | 亚洲美女在线播放 | 在线日本视频 | 丁香婷婷影音先锋5566 | 欧美在线一级精品 | 国产成人一区二区三区免费观看 | 亚洲最大网站在线 | 涩涩国产精品福利在线观看 |