Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 10 ■ SPL ITERATORS^145

1

2

3

■Note Instead of writing out a foreach loop to see the contents of your iterator, you could also use the
function iterator_to_array($iterator), as described in Chapter 9.

OuterIterator
Sometimes it is advantageous to enclose one or more iterators in another iterator, such as
when you want to sequentially iterate several different iterators (which you can do with the
AppendIterator, as discussed later in this chapter). For this purpose, you can use the OuterIterator
interface.
The definition of the OuterIterator interface is as follows:

interface OuterIterator extends Iterator {
function getInnerIterator();
}

This interface differs from the IteratorAggregate interface in that it extends the Iterator
interface; thus, any class implementing it must also implement all the Iterator-defined methods.
The getInnerIterator() method should return the currently iterating iterator. For example,
when two or more iterators are appended together and iterated one after the other, the
getInnerIterator() method must return the first iterator, then the second, and so on, as the
array pointer is increased by the next() method.
This interface forms the base interface for several more specialized iterators, including
AppendIterator, CachingIterator, FilterIterator, IteratorIterator, LimitIterator, and
RecursiveIteratorIterator.

RecursiveIterator
The RecursiveIterator interface is designed to allow for recursive iteration. This type of iter-
ator interface can represent a tree data structure with nodes and leaves or parent and child
elements. A directory is an example of a recursive structure.
The definition of the RecursiveIterator interface is as follows:

interface RecursiveIterator extends Iterator {
function hasChildren();
function getChildren();
}

All recursive functions (functions that call themselves) must have the ability to determine
whether to continue recursing or to stop recursing and return to the top of the call stack. The
hasChildren() method allows for this condition. If the iterator has children, the getChildren()
method will be called, and it should return an iterator instance for the child elements.

McArthur_819-9C10.fm Page 145 Friday, February 22, 2008 9:08 AM

Free download pdf