PHP 5 and Iterator Beauty

PHP Logo

As a default behavior in PHP 5, using an object in a foreach structure will traverse all public values. Multiple Iterator classes are available with PHP to allow you to iterate through common lists, such as directories, XML structures and recursive arrays. It’s possible to define your own Iterator classes by implementing the Iterator interface, which will override the default behavior. Using this method will allow great flexibility in data management and give a great opportunity to draw a line between display logic and buisness logic without having to generate an array containing all the data as it was required before to use foreach.

It also avoids using the while loop method which was based on the fact that a function could return values of multiple types. It’s not a bad method on it’s own, it actually loops clean enough, but if PHP ever want to be able to interact with other languages naturally, or the other way around, those methods are to be avoided.

The remaining section describes the technical aspects of the Iterator interface.

The Interface definition of the Iterator interface would look like this if it could be found anywhere.

 interface Iterator {     // Returns the current value     function current();     // Returns the current key     function key();     // Moves the internal pointer to the next element     function next();     // Moves the internal pointer to the first element     function rewind();     // If the current element is valid (boolean)     function valid(); } 

These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:

  1. rewind()
  2. if valid() then 3 else 6
  3. current() in $value
  4. key() in $key
  5. next()
  6. End of Loop

According to Zend, the current() method is called before and after the valid() method.

Leave a Reply

Your email address will not be published. Required fields are marked *