Pro PHP- Patterns, Frameworks, Testing and More

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

$iterator = new RegexIterator(
$arrIterator,
'/^\d*$/',
RegexIterator::MATCH,
RegexIterator::USE_KEY
);
print_r(iterator_to_array($iterator));

Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)

The final RegexIterator parameter, $preg_flags, is used to pass any of the usual preg
parameters to the underlying preg functions.

IteratorIterator
The IteratorIterator is actually one of the coolest iterators provided by SPL, though it’s defi-
nitely hard at first to understand why.
The IteratorIterator is a nonspecific iterator type of iterator, which means that anything
that implements Traversable can be iterated. This might not immediately seem useful, but
various PHP extensions have classes that, for various good reasons, do not implement Iterator
or IteratorAggregate but do implement Traversable.
One such example is the PHP Data Objects (PDO) extension. In PDO, the PDOStatement
class implements only Traversable because it is a read-only collection, and because of this, the
higher level iterators are not appropriate. The result of this read-only limitation is that to combine
the result of a PDOStatement with any of the other iterators described in this chapter, you will
need to use the IteratorIterator to wrap the PDOStatement.

■Note PDO is an extension you may already be familiar with, but if you need a refresher, it is covered very
well in W. Jason Gilmore’s book, Beginning PHP and MySQL 5, Second Edition (Apress, 2006; 1-59059-552-1).

Certain modifying iterators, like RegexIterator, may cause problems due to PDOStatement’s
read-only nature, and as such, they should not be used. That said, several useful iterators—like
AppendIterator, FilterIterator, and LimitIterator—can be very useful when combined with
PDOStatement result sets. Listing 10-10 shows how to use IteratorIterator and LimitIterator
to limit a result set.

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

Free download pdf