How does the PHP IteratorIterator class work?
- by WilliamMartin
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.