Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding OuterIterator Interface PHP

Tags:

iterator

php

spl

I'm trying to implement OuterIterator interface on my class but I'm not sure what to use in the method getInnerIterator. I know it should return an Iterator but I'm not understanding in what circumstances it should return an InnerIterator although it is already has all the methods of the Iterator interface then why does it need an InnerIterator?

I'm totally lost with OuterIterator

class myouterIterator implements OuterIterator 
{
    /**
    * Returns the inner Iterator for the current entry
    */
    public $data = array(1,2,3,4,5,6,7,8,9,10);
    public $position = 0;
    public function getInnerIterator()
    {
        // What code should be place here
    }
    public function rewind()
    {
        $this->position = 0;
    }
    public function valid()
    {
        return isset($this->data[$this->position]);
    }
    public function key()
    {
        return $this->position;
    }
    public function current()
    {
        return $this->data[$this->position];
    }
    public function next()
    {
        ++$this->position;
    }
}   

$OuterIt = new myouterIterator();
foreach($OuterIt as $key => $value)
{
    echo $key, ' ', $value, '<br>';

}
like image 994
Daric Avatar asked Oct 22 '22 17:10

Daric


1 Answers

Why do you want to implement OuterIterator at all? It is intended to "iterate over iterators" but your example just iterates over scalar values, it makes no sense to have an iterator for each of them.

If you want to see a practical example of the OuterIterator interface, have a look at the AppendIterator, which consecutively iterates over several iterators.

like image 51
Fabian Schmengler Avatar answered Nov 03 '22 00:11

Fabian Schmengler