I am trying to understand what getIterator() is, I will explain:
As I know getIterator is a method we call to include an external Iterator.
The problem is getIterator include it’s own methods the closes think looks the same is Iterator interface but it can’t be an interface it can be class but i am trying to search it inside the SPL.php source code and didn’t find any, maybe I’m making this more complicated than it’s really is, I will be happy if some one can help me understand where it is at the SPL.php source code and what is it (class,etc). Thank you all and have a nice day.
ArrayObjectimplementsIteratorAggregatewhich allows you to return an iterator instead of implementing it. It’s pretty straightforward. Assume you have a class wrapping an array, likeand you want to
foreachover an instance ofFoo, like this:To achieve that you could add the
Iteratorinterface but then you’d had to implement all the methods in the interface for the simple task of iterating the array inside the object. You dont want to duplicate that code over and over again whenever you need that functionality, especially since there already is an Iterator that does what you want. So instead of implementingIteratoryou implementIteratorAggregateNow when you do the
foreachPHP will use the Iterator returned fromgetIteratorinstead of theFooinstance itself allowing you to get the output 1234.In case of
ArrayObject, the point is simply for allowing you toforeachover the values in theArrayObject. Of course, you can also callgetIteratoryourself, since it’s public and then use returned Iterator directly.Also note the ctor signature of
ArrayObject:which notes which Iterator will be returned.