php mysql迭代器_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的书目:"."";

$this->toString($bookaiterator);

echo "";

$bookbiterator = $this->bookstring->getIterator();

echo "书店B的书目:"."";

$this->toString($bookbiterator);

}

public function toString(NewIterator $_iterator){

while ($_iterator->hasNext()){

echo $_iterator->Next()."";

}

}

}

$booka=new BookA();

$bookb=new BookB();

$a = new BookList($booka,$bookb);

$a->Menu();

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值