phpiteratorspl

Why must I rewind IteratorIterator


$arrayIter = new ArrayIterator( array(1, 2) );
$iterIter = new IteratorIterator($arrayIter);

var_dump($iterIter->valid()); //false
var_dump($arrayIter->valid()); //true

If I first call $iterIter->rewind(), then $iterIter->valid() is true. I'm curious why it requires that rewind() be called. I imagine there's good reason for it, but I would have expected it to simply start iteration at whatever state it's inner iterator is in, and leave it as an option to rewind before beginning iteration.

calling next() also seems to put it in a "valid" state(although it advances to the next position, suggesting it was previously at the first position).

$arrayIter = new ArrayIterator(array(1,2));
$iterIter = new IteratorIterator($arrayIter);

$iterIter->next();
var_dump($iterIter->valid()); 

Again, I'm curious why I need to call rewind(), despite the inner iterator being in a valid state.


Solution

  • With a fresh iterator the position isn't initialized, simply for performance reasons. You can stack iterators on top of other iterators. If all of them would rewind during construction there would be some performance impact. Additionally, some iterators might change their first value after the constructor was executed, which is unknown to iterators further out.

    Iterators are usually executed by foreach() which does a rewind() first.