首页 > 代码库 > PHP实现迭代器
PHP实现迭代器
不多说,对于PHP的新手来说,学习到了。
<?php /** * 迭代器的公用接口 */ interface NewIterator{ public function hasNext(); public function Next(); } /** * 书目的迭代器,实现NewIterator接口 */ class BookIterator implements NewIterator { private $array = array();//记录整个内容 private $num = 0;//记录索引 public function __construct($_string){ //因为在我的例子里需要这样处理。 if (is_array($_string)){ $this->array = $_string; }else{ $this->array = explode("|",$_string); } } public function next(){ //记录下一项的内容 $arrayA = $this->array[$this->num]; //索引增加1 $this->num = $this->num + 1; return $arrayA; } public function hasNext(){ if($this->num >= count($this->array) || $this->array[$this->num] == null){ return false; }else{ return true; } } } /** * 数目是用数组存储的 */ class BookA{ private $bookarray = array(); public function __construct(){ $this->addItem("深入浅出设计模式"); $this->addItem("think in java"); $this->addItem("php手册"); } public function addItem($_string){ $this->bookarray[]=$_string; } //这里不再返回一个数组。而是一个真正的对象。数组被传递到了迭代器中。实现和书目调用的解耦 public function getIterator(){ return new BookIterator($this->bookarray); } } /** * 书目都是用字符串存储的 */ class BookB{ private $bookindex=""; public function __construct(){ $this->addItem("深入浅出设计模式"); $this->addItem("PHP"); $this->addItem("think in java"); } public function addItem($_string){ $this->bookindex.="|".$_string; } public function getIterator(){ return new BookIterator(trim($this->bookindex,"|"));//附带的处理而已 } } /** * 输出两个书店的书目 // */ //require "NewIterator.php"; //require ‘BookA.php‘; //require ‘BookB.php‘; //require "BookIterator.php"; class BookList{ private $bookarray; private $bookstring; public function __construct(BookA $_booka,BookB $_bookb){ $this->bookarray = $_booka; $this->bookstring = $_bookb; //改装成了只记录对象引用; } public function Menu(){ $bookaiterator = $this->bookarray->getIterator(); echo "书店A的书目:"."</br>"; $this->toString($bookaiterator); echo "</br>"; $bookbiterator = $this->bookstring->getIterator(); echo "书店B的书目:"."</br>"; $this->toString($bookbiterator); } public function toString(NewIterator $_iterator){ while ($_iterator->hasNext()){ echo $_iterator->Next()."</br>"; } } } $booka=new BookA(); $bookb=new BookB(); $a = new BookList($booka,$bookb); $a->Menu(); ?>
PHP实现迭代器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。