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.