PHP実現反復器

2649 ワード

言うまでもなく、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();

?>