PHP實現迭代器

來源:互聯網
上載者:User

標籤:io   os   java   ar   sp   cti   on   c   ad   

不多說,對於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個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.