Improving the Collection Class

Improving the Collection Class

"Improve the Collection class? Impossible! How could it possibly be more powerful, useful, or exciting?" you ask. Well, the problem is that you don't yet have a simple way to iterate over the entire collection, displaying a list of the courses, for example. Right now, you can jump directly only to those items that you already know are in the collection. Obviously, you don't always know what the contents of the collection are before you set out to use it, so you need a way to write code like this:

   <?php    $objStudent = StudentFactory::getStudent(1);    foreach($objStudent->courses as $objCourse) {      print $objStudent.'is currently enrolled in ' . $objCourse . '<br>\n";    }    ?> 

If you were to try to run that code now, you would either get an error or see nothing at all (depending on the error_reporting level) because $objStudent->courses is not an array, it's a Collection.In PHP4, the only data type that could be used as the operand of a foreach statement was an array. In PHP5 you have two new built-in interfaces, called Iterator and IteratorAggregate, that allow you to use foreach on objects, so long as they implement those interfaces.

These two interfaces are the topic of the next chapter, so read on and learn how to make the Collection class even more useful!

Professional PHP5 (Programmer to Programmer Series)
Professional PHP5 (Programmer to Programmer Series)
Year: 2003
Pages: 182
BUY ON AMAZON © 2008-2017.
If you may any questions please contact us: