Пример реализации интератора range
<?php class RangeIterator implements Iterator { protected $start; protected $end; protected $step; protected $key; protected $value; public function __construct($start, $end, $step = 1) { $this->start = $start; $this->end = $end; $this->step = $step; } public function rewind() { $this->key = 0; $this->value = $this->start; } public function valid() { return $this->value < $this->end; } public function next() { $this->value += $this->step; $this->key += 1; } public function current() { return $this->value; } public function key() { return $this->key; } } $interator = new RangeIterator(0, 11); foreach($interator as $item){ echo (string) $item . "\n"; }
Вывод
php ./interator.php 0 1 2 3 4 5 6 7 8 9 10
Пример интератора (перебор данных файла) (к сожалению не рабочий и в таком случае нада использовать генератор)
class FileIterator implements Iterator { protected $f; public function __construct($file) { $this->f = fopen($file, 'r'); if (!$this->f) throw new Exception(); } public function current() { return fgets($this->f); } public function key() { return ftell($this->f); } public function next() { } public function rewind() { fseek($this->f, 0); } public function valid() { return !feof($this->f); } } $file = new FileIterator($path); foreach($file as $line_nunmber => $line_value){ // do it }