Search code examples
phpiteratorsimplexmlspl

How does the PHP IteratorIterator class work?


Try as I might I cannot get my head around what the IteratorIterator class actually does. I understand that classes can implement Traversable so the engine knows it can loop using foreach and I realise that IteratorIterator is supposed to convert anything that is Traversable into an Iterator but I cannot for the life of me understand how.

Take for example, the PDOStatement class; how would the standard Iterator methods (next, key, rewind, etc) be implemented to allow iteration over a PDOStatement?

Sorry if my question is unclear, I am just struggling to grasp the exact reason for this class and the documentation on it is scant.

Thanks,

Will

Update: Going through the phpt files, I found one test which uses IteratorIterator:

<?php

$root = simplexml_load_string('<?xml version="1.0"?>
<root>
    <child>Hello</child>
    <child>World</child>
</root>
');

foreach (new IteratorIterator($root->child) as $child) {
    echo $child."\n";
}

?>

The expected output is:

Hello
World

I don't really follow how the IteratorIterator construct takes $root->child as an argument and how it manages to iterate over the child elements.


Solution

  • Based on this, I think it allows you to Iterate over Iterated objects. I.e. you can pull other objects in your master object and using IteratorIterator on your master object, Iterate the child objects as well.

    UPDATE: Based on your update. This makes sense to me, though there is only one root object, so iterating it doesn't really apply in this example, but you could if there were more root objects. In other words, I believe IteratorIterator is the same as having nested foreach loops, without having to know all of the elements of each object. In other words, a nested foreach using object oriented objects... there's a redundant statement. :-)