Pro PHP- Patterns, Frameworks, Testing and More

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

This iterator also provides a static compareIterators($lhs, $rhs, $identical=false)
method that can compare two iterators for equality or identicalness.
During iteration, the iterator provides two methods that allow you to access the right-hand
and left-hand iterators: getLHS() and getRHS(). It also offers two methods that compare these
values: areEqual() and areIdentical().
Listing 10-15 demonstrates using the DualIterator.

Listing 10-15. Using a DualIterator Iterator

require_once('/path/to/php-src/ext/spl/examples/dualiterator.inc');

$arrayIterator1 = new ArrayIterator(array(true, false, true));
$arrayIterator2 = new ArrayIterator(array(1, 0, true));

$it = new DualIterator($arrayIterator1, $arrayIterator2);

foreach($it as $unused) {
echo "Left: ". (($it->getLHS()->current())?'true':'false');
echo " Right: ". (($it->getRHS()->current())?'true':'false');
echo " Equal: ". (($it->areEqual())?'true':'false');
echo " Identical: ". (($it->areIdentical())?'true':'false');
echo "\n";
}

echo "\nIterators Equal:";
var_dump(DualIterator::compareIterators($arrayIterator1, $arrayIterator2, false));
echo "\nIterators Identical:";
var_dump(DualIterator::compareIterators($arrayIterator1, $arrayIterator2, true));

Left: true Right: true Equal: true Identical: false
Left: false Right: false Equal: true Identical: false
Left: true Right: true Equal: true Identical: true

Iterators Equal:bool(true)

Iterators Identical:bool(false)

You can also use the compareIterators() method to see if an iterator-returning method
returned a valid iterator or an EmptyIterator by comparing the return value to a new
EmptyIterator().

RecursiveFilterIterator
The RecursiveFilterIterator is the recursive form of the FilterIterator. It requires you to
implement the abstract accept() method as before, but inside this method, you should access
the currently iterating iterator using the $this->getInnerIterator() method.

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

Free download pdf