zephir icon indicating copy to clipboard operation
zephir copied to clipboard

ArrayIterator and `for` loop

Open mruz opened this issue 11 years ago • 4 comments

I have simple Arr helper with getIterator() method:

class Arr implements \ArrayAccess, \Countable, \IteratorAggregate
{

    protected _data = [] { get };

    public function getIterator()
    {
        return new \ArrayIterator(this->_data);
    }
    //...

Is it possible to ArrayIterator work with for loop?

let tokens = new Arr([1,2,3]);

for token in tokens {
    var_dump(token);
}

The argument is not initialized or iterable()

So I must use:

for token in tokens->getData() {
    var_dump(token);
}

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/5760323-arrayiterator-and-for-loop?utm_campaign=plugin&utm_content=tracker%2F280146&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F280146&utm_medium=issues&utm_source=github).

mruz avatar Nov 04 '14 16:11 mruz

This way:

for token in iterator(tokens) {
    var_dump(token);
}

Remember that for questions like this you can better use the forum: http://forum.zephir-lang.com/

phalcon avatar Nov 04 '14 16:11 phalcon

Thanks, I didn't know about the forum.

Could Zephir auto-detect if object have getIterator() method? What do you think?

mruz avatar Nov 04 '14 17:11 mruz

You mean at compile time or runtime?

phalcon avatar Nov 12 '14 22:11 phalcon

At compile time, before error check if argument has iterator.

mruz avatar Nov 13 '14 00:11 mruz