How does the PHP IteratorIterator class work?

Posted by WilliamMartin on Stack Overflow See other posts from Stack Overflow or by WilliamMartin
Published on 2009-09-02T10:33:26Z Indexed on 2010/06/06 1:02 UTC
Read the original article Hit count: 300

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about php

Related posts about iterator