PHP中迭代器的简单实现及Yii框架中的迭代器实现方法示例
本文实例讲述了PHP中迭代器的简单实现及Yii框架中的迭代器实现方法。分享给大家供大家参考,具体如下:
在维基百科中我们可以看到其定义如下:
迭代器有时又称光标(cursor)是程式设计的软件设计模式,可在容器物件(container,例如list或vector)上遍访的接口,设计人员无需关心容器物件的内容。
各种语言实作Iterator的方式皆不尽同,有些面向对象语言像Java,C#,Python,Delphi都已将Iterator的特性内建语言当中,完美的跟语言整合,我们称之隐式迭代器(implicititerator),但像是C++语言本身就没有Iterator的特色,但STL仍利用template实作了功能强大的iterator。
Iterator另一方面还可以整合Generator。有些语言将二者视为同一接口,有些语言则将之独立化。
地址:http://zh.wikipedia.org/zh-cn/%E8%BF%AD%E4%BB%A3%E5%99%A8
【Iterator的简单实现】
/**
*Iterator模式的简单实现类
*/
classsampleimplementsIterator{
private$_items;
publicfunction__construct(&$data){
$this->_items=$data;
}
publicfunctioncurrent(){
returncurrent($this->_items);
}
publicfunctionnext(){
next($this->_items);
}
publicfunctionkey(){
returnkey($this->_items);
}
publicfunctionrewind(){
reset($this->_items);
}
publicfunctionvalid(){
return($this->current()!==FALSE);
}
}
/**DEMO*/
$data=array(1,2,3,4,5);
$sa=newsample($data);
foreach($saAS$key=>$row){
echo$key,'',$row,'
';
}
在next()方法的实现时有过纠结,一直以为这里需要返回下一个的值,
这是因为一直以为这里的next就是next函数的实现,但是非也
在手册中我们可以看到其定义为
abstractpublicvoidIterator::next(void)
其返回值类型为void
所以这里我们调用next函数就可以了,没有必要返回
另外,以上实现对于如下的数组是存在的问题
$data=array('0'=>11,""=>22,'s3'=>33,0,0,"",false,0,1);
运行结果是输出:
011
22
s333
10
20
3
false后面的值就没有迭代显示出来了,具体原因还不清楚,留作下回分解
在yii框架中也有实现迭代器,它的实现避免了这个问题。
【Yii框架中的迭代器实现】
在Yii框架中的我们可以看到其迭代器的实现
在collections目录下的CMapIterator.php文件中,其实现如下:
classCMapIteratorimplementsIterator{
/**
*@vararraythedatatobeiteratedthrough
*/
private$_d;
/**
*@vararraylistofkeysinthemap
*/
private$_keys;
/**
*@varmixedcurrentkey
*/
private$_key;
/**
*Constructor.
*@paramarraythedatatobeiteratedthrough
*/
publicfunction__construct(&$data){
$this->_d=&$data;
$this->_keys=array_keys($data);
}
/**
*Rewindsinternalarraypointer.
*ThismethodisrequiredbytheinterfaceIterator.
*/
publicfunctionrewind(){
$this->_key=reset($this->_keys);
}
/**
*Returnsthekeyofthecurrentarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnmixedthekeyofthecurrentarrayelement
*/
publicfunctionkey(){
return$this->_key;
}
/**
*Returnsthecurrentarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnmixedthecurrentarrayelement
*/
publicfunctioncurrent(){
return$this->_d[$this->_key];
}
/**
*Movestheinternalpointertothenextarrayelement.
*ThismethodisrequiredbytheinterfaceIterator.
*/
publicfunctionnext(){
$this->_key=next($this->_keys);
}
/**
*Returnswhetherthereisanelementatcurrentposition.
*ThismethodisrequiredbytheinterfaceIterator.
*@returnboolean
*/
publicfunctionvalid(){
return$this->_key!==false;
}
}
$data=array('s1'=>11,'s2'=>22,'s3'=>33);
$it=newCMapIterator($data);
foreach($itas$row){
echo$row,'
';
}
这与之前的简单实现相比,其位置的变化是通过控制key来实现的,这种实现的作用是为了避免false作为数组值时无法迭代
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。