In simple words this design pattern is a solution to traverse or iterate through an aggregate object i.e. an object which acts as a list or container and stores other objects. As you walk through the list of songs in your mobile phone or MP3 player, this pattern helps you traverse through the items of the container object.

Generally when there is the need of storing items in a list we use an array and using loops we iterate through each element of an array. While this solution works, it is the native way of iterating through a list but not an object oriented reusable solution. Design patterns deal with object oriented solution and the Iterator pattern is the way to traverse through a collection in the object oriented domain. The Iterator pattern suggests providing an interface which you can implement in other classes. Moreover, in the concrete implementation of the interface functions you can manipulate the items in the list as per your need.

Suppose we have a movie class and we want to create a movie list. So we would like to iterate through the movie list. For this we will just pass the aggregate object containing the list to an instance of MovieListIterator class and using that we can iterate through the movies present in the list. Below is the example code:

Output

Movie: Inception (2010)
Movie: Avatar (2009)
Movie: Man of Steel (2013)
Movie: Up (2009)
Movie: Bee Movie (2007)

The advantage of using Iterate pattern is that you can create any number of iterator classes for the movie list and in each of them you can provide different definition of the way you would like to traverse through the collection. For example if you would like to iterate through a sorted movie list object, just extend another class from the base iterator class and change the code as per your need. Below is the example code:

Now instead of passing the movie list object to the MovieListIterator instance, pass it to the SortedMovieListIterator instance and use the instance to iterate the list. It will output the movies in the sorted order.

Output

Movie: Avatar (2009)
Movie: Bee Movie (2007)
Movie: Inception (2010)
Movie: Man of Steel (2013)
Movie: Up (2009)

Starting from version 5, PHP has an Iterator interface built into it. So it can be implemented by any class you create. Check out the PHP manual of the Iterator interface.