Chapter 6: CollectionIterator Class

Overview

The previous chapter gave you a look at the Collection class, an object-oriented (OO) wrapper for managing an array of objects that's a powerful and flexible part of the utility toolkit. On its own, however, it is missing some functionality. Namely, it does not provide an easy way to iterate over all its members. In the example application we saw in the previous chapter (a university registrar's office), there existed a Student class that has a member variable called courses, which is a Collection. In this application, you would likely need a view that displays a list of all the courses for which a student is registered. To keep the syntax as simple as possible, ideally you should be able to do something like the following:

   <?php      $objStudent = new Student(12345);      foreach($objStudent->classes as $objClass) {        print $objClass . "\n";      }    ?> 

If you have some experience with PHP4, you'll recognize the foreach statement as a construct that allows you to easily traverse the elements of an array. In PHP4, the only valid operand to foreach was an array. Any other data type caused a runtime error.

PHP5 has a way to allow foreach to work on objects, too. The built-in interfaces Iterator and IteratorAggregate work together to allow you to traverse the elements of an object that contains other objects, such as our Collection class.

In this short chapter, you'll learn how to use these interfaces to enable your classes in exactly this manner, so that the foreach iteration method becomes just as useful for traversing collections of objects as it has always been for traversing regular arrays.



Professional PHP5 (Programmer to Programmer Series)
Professional PHP5 (Programmer to Programmer Series)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 182
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net