什么是PHP中的对象迭代

Can anyone explain what is object iteration and how this code works?


class MyIterator implements Iterator{
   private $var = array();
   public function __construct($array){
       if (is_array($array)) {
           $this->var = $array;
       }
   }
   public function rewind() {
       echo "rewinding
"; reset($this->var); } public function key() { $var = key($this->var); echo "key: $var
"; return $var; } public function next() { $var = next($this->var); echo "next: $var
"; return $var; } public function valid() { $var = $this->current() !== false; echo "valid: {$var}
"; return $var; } public function current() { $var = current($this->var); echo "current: $var
"; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach ($it as $a => $b) { print "$a: $b
"; }

The Iterator interface is probably inspired from the Java Iterators. It provides a generic interface to continuously iterate over a list of items using the foreach construct.

Your code defines a class which implements this interface. It basically provides the same functionality as an array natively supports, but adds some echo statements.

Why use iterators?

The advantage of the Iterator is that it provides a high-level abstracted interface, so the code that calls it does not need to worry so much about what is going on. At the same time it allows you to process large data sources (fetching rows from a db, reading lines from a file) in chunks without having to load everything into memory at once.