php[world] 2015 Schedule Announced

The IteratorIterator class

(PHP 5 >= 5.1.0)

Introduction

This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.

Class synopsis

IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Traversable $iterator )
public mixed current ( void )
public Traversable getInnerIterator ( void )
public scalar key ( void )
public void next ( void )
public void rewind ( void )
public bool valid ( void )
}

Table of Contents

add a note add a note

User Contributed Notes 1 note

up
0
sven at rtbg dot de
2 months ago
This iterator basically is only a wrapper around another iterator. It does nothing fancy, it simply forwards any calls of rewind(), next(), valid(), current() and key() to the inner iterator. This inner iterator can be fetched with getInnerIterator().

One special case: When passing an IteratorAggregate object, the getIterator() method of that object will be called and THAT iterator will be iterated over, and this will also be returned when calling getInnerIterator().

This class can be extended, so it's an ideal building block for your own classes that only want to modify one or two of the iterator methods, but not all.

Want to trim the strings returned by the current() method?

<?php

class TrimIterator extends IteratorIterator
{
    public function
current() {
        return
trim(parent::current());
    }
}

$innerIterator = new ArrayIterator(array('normal', ' trimmable '));

$trim = new TrimIterator($innerIterator);

foreach (
$trim as $key => $value) {
    echo
"Key:\n";
   
var_dump($key);
    echo
"Value:\n";
   
var_dump($value);
    echo
"---next---";
}
?>

Output:

Key:
int(0)
Value:
string(6) "normal"
---next---Key:
int(1)
Value:
string(9) "trimmable"
---next---
To Top