Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^148) CHAPTER 10 ■ SPL ITERATORS
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
■Note The PHP 5.2.1 and later $use_keys parameter to iterator_to_array() was used in Listing 10-5 to
prevent the array keys from the first iterator being overwritten by the second. If you did not provide this param-
eter, the result would be array(0=>4,1=>5), because 0=>1 and 1=>2 are defined and then overwritten with
the values from the second iterator.
FilterIterator
The FilterIterator class is an OuterIterator-based iterator. It is used to filter the data in an
iterator and return any elements that are acceptable. For example, FilterIterator could be
used in conjunction with DirectoryIterator to return a list of large files.
This class has one abstract method, accept(), which must be implemented. Because of
this, the FilterIterator is usable only as a base class. The accept() method must return true
or false for the current item in the iterator. If the return result is true, then that record will be
included in the iteration. If it is false, it will be excluded from iteration.
Listing 10-6 demonstrates filtering with a FilterIterator.
Listing 10-6. Using a FilterIterator Iterator
class GreaterThanThreeFilterIterator extends FilterIterator {
public function accept() {
return ($this->current() > 3);
}
}
$arr = new ArrayIterator(array(1,2,3,4,5,6));
$iterator = new GreaterThanThreeFilterIterator($arr);
print_r(iterator_to_array($iterator));
Array
(
[3] => 4
[4] => 5
[5] => 6
)
McArthur_819-9C10.fm Page 148 Friday, February 22, 2008 9:08 AM

Free download pdf