Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayObject, getIterator();

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.

like image 363
Aviel Fedida Avatar asked Jul 07 '12 07:07

Aviel Fedida


1 Answers

ArrayObject implements IteratorAggregate which allows you to return an iterator instead of implementing it. It's pretty straightforward. Assume you have a class wrapping an array, like

class Foo
{
    private $array = [1,2,3,4];
}

and you want to foreach over an instance of Foo, like this:

foreach (new Foo as $bar) {
    echo $bar; // outputs 1234
}

To achieve that you could add the Iterator interface 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 implementing Iterator you implement IteratorAggregate

class Foo implements IteratorAggregate
{
    private $array = [1,2,3,4];

    public function getIterator()
    {
        return new ArrayIterator($this->array);
    }
}

Now when you do the foreach PHP will use the Iterator returned from getIterator instead of the Foo instance itself allowing you to get the output 1234.

In case of ArrayObject, the point is simply for allowing you to foreach over the values in the ArrayObject. Of course, you can also call getIterator yourself, since it's public and then use returned Iterator directly.

Also note the ctor signature of ArrayObject:

public __construct (
    [ mixed $input 
    [, int $flags = 0 
    [, string $iterator_class = "ArrayIterator" 
]]] )

which notes which Iterator will be returned.

like image 189
Gordon Avatar answered Oct 10 '22 07:10

Gordon