Iteratorパターン

PHP5.1.6環境でPHP4スタイルで書きました。PHP5からは組み込みのIteratorがあるらしいけれど、基本的なことを学ぶのが目的なのでなるべくそういった便利さは省く。

<?php
class Aggregate {
  function myiterator(){
    die("can not do this");
  }
}
class MyIterator {
  function hasNext(){
    die();
  }
  function next(){
    die();
  }
}
class Foo extends Aggregate {
  var $items;
  var $last;
  function Foo(){
    $this->items = array();
    $this->last = 0;
  }
  function add($item){
    $this->items[$this->last] = $item;
    $this->last++;
  }
  function getFooAt($index){
    return $this->items[$index];
  }
  function myiterator(){
    return new FooIterator($this);
  }
}
class FooIterator extends MyIterator {
  var $foo;
  var $index;
  function FooIterator($foo){
    $this->foo = $foo;
    $this->index = 0;
  }
  function hasNext(){
    if($this->index < $this->foo->last){
      return 1;
    } else {
      return 0;
    }
  }
  function next(){
    $item = $this->foo->getFooAt($this->index);
    $this->index++;
    return $item;
  }
}

$foo = new Foo;
$foo->add('hoge');
$foo->add('hogemoge');
$it = $foo->myiterator();
while($it->hasNext()){
  $item = $it->next();
  print $item."\n";
}
//print_r($foo);
//print_r($it);
?>