5

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>';

}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.