PHP SPL ArrayIterator v simple foreach

Well, as the name says: what are the main advantages of using ArrayIterator over a simple foreach loop.

I have an object that is used as a container, its main responsibility is to store an array of objects.

Someone suggested I implement my IteratorAggregate class and return an ArrayIterator with my array of objects in: for example:

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

I do not see any advantages for this, and not just for returning the array, and then using the standard foreach to iterate over them.

Please explain why this would be a good idea?

+5
source share
2 answers

An array return provides the internal structure of an object. Using an iterator is more abstract.

, . , , .

-2

ArrayAccess : , private .

Iterator ArrayAccess $array.

class Foo implements \ArrayAccess, \Iterator
{
    public $pointer = 0;

    private $array = [
        'first value',
        'second value',
        'third value',
    ];

    public function __construct()
    {
        $this->pointer = 0;
    }

    public function current()
    {
        return $this->array[ $this->pointer ];
    }

    public function key()
    {
        return $this->pointer;
    }

    public function next()
    {
        ++$this->pointer;
    }

    public function rewind()
    {
        $this->pointer = 0;
    }

    public function valid()
    {
        return isset( $this->array[ $this->position ] );
    }
}

, :

$foo = new Foo();
foreach ( $foo as $key => $value )
{
    print "Index: {$key} - Value: {$value}".PHP_EOL;
}

, , . ArrayAccess, , :

ArrayAccess {
    abstract public boolean offsetExists ( mixed $offset )
    abstract public mixed offsetGet ( mixed $offset )
    abstract public void offsetSet ( mixed $offset , mixed $value )
    abstract public void offsetUnset ( mixed $offset )
}

(current/key/next/etc) , IteratorAggregate. : getIterator().

:

class Bar implements \ArrayAccess, \IteratorAggregate
{
    private $array = [];

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

$array. , , isset, .. . , , IteratorAggregate.

: , , Traversable. , Iterator, IteratorAggregate , , -. , , .

$foo = new IteratorContainerController();
$foo->addDependency( Traversable $bar );

, Dependency IteratorContainerController() Iterator, IteratorAggregate. , - IteratorAggregate , / , / Iterator.

+7

All Articles