PHP设计模式入门之迭代器模式原理与实现方法分
网络编程 2021-07-04 23:05www.168986.cn编程入门
这篇文章主要介绍了PHP设计模式入门之迭代器模式原理与实现方法,结合实例形式分析了PHP迭代器模式基本概念、原理、实现方法及操作注意事项,需要的朋友可以参考下
本文实例讲述了PHP设计模式入门之迭代器模式。分享给大家供大家参考,具体如下
在深入研究这个设计模式之前,我们先来看一道面试题,来自鸟哥的博客,
题目是这样的
使对象可以像数组一样进行foreach循环,要求属性必须是私有。
不使用迭代器模式很难实现,先看实现的代码
sample.php
<?php class Sample implements Iterator{ private $_arr; public function __construct(Array $arr){ $this->_arr = $arr; } public function current(){ return current($this->_arr); } public function next(){ return next($this->_arr); } public function key(){ return key($this->_arr); } public function valid(){ return $this->current() !== false; } public function rewind(){ reset($this->_arr); } }
index.php
<?php require 'Sample.php'; $arr = new Sample(['max', 'ben', 'will']); foreach ($arr as $k=>$v){ echo $k."-".$v."<br />"; }
其中Iterator接口来自php的spl类库,在写完设计模式的相关文章之后,将会进一步研究这个类库。
在网上找到了一段yii框架中关于迭代器模式的实现代码
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 />'; }
关于迭代器设计模式官方的定义是使用迭代器模式来提供对聚合对象的统一存取,即提供一个外部的迭代器来对聚合对象进行访问和遍历 , 而又不需暴露该对象的内部结构。又叫做游标(Cursor)模式。
好吧,我不是很能理解。为什么明明数组已经可以用foreach来遍历了还要用这样一种迭代器模式来实现,只有等待工作经验的加深来进一步理解吧。
参考文档
更多关于PHP相关内容感兴趣的读者可查看本站专题《》、《》、《》、《》、《》、《》及《》
希望本文所述对大家PHP程序设计有所帮助。
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指