Iterator(Aggregate)インターフェイス

 <?php
 class MyArray implements IteratorAggregate {
     private $array = array(1,2,3);
 
     public function __construct() {
         $this->array[] = 10;
     }
 
     public function getIterator() {
         return new MyIterator($this->array);
     }
 }
 
 class MyIterator implements Iterator {
     private $position = 0;
 
     public function __construct($array) {
         $this->array = $array;
         $this->position = 0;
     }
 
     function rewind() {
         $this->position = 0;
     }
 
     function current() {
         return "VAL: " . $this->array[$this->position];
     }
 
     function key() {
         return "KEY: " . $this->position;
     }
 
     function next() {
         ++$this->position;
     }
 
     function valid() {
         return isset($this->array[$this->position]);
     }
 }
 $obj = new MyArray;
  
 foreach($obj as $key => $val) {
     print "$key , $val\n";
 }

参考


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS