2017-07-03 17:27 GMT+02:00 Johannes Schlüter <johan...@schlueters.de>:

> On Sa, 2017-07-01 at 19:38 +0200, Andreas Hennings wrote:
> > Hello internals,
> > (this is my first email to this list, hopefully I'm doing ok.)
> >
> > -------------------------------------------------------------------
> > -------------
> >
> > Background / motivation:
> >
> > Currently in PHP we have an interface "Iterator", and a final class
> > "Generator"
> > (and others) that implement it.
> >
> > Using an iterator in foreach () is straightforward:
> > foreach ($iterator as $key => $value) {..}
> >
> > However, if we want to iterate only a portion and then continue
> > elsewhere at the position where we stopped, we need to do something
> > like this:
> >
> > for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
> >   $value = $iterator->current();
> >   [..]
> > }
> >
> > This is unpleasantly verbose, and also adds performance overhead due
> > to additional function calls.
>
> Wouldn't SPL's NoRewindIterator be enough?
>
> $nit = new NoRewindIterator($it);
>
> foreach ($nit as $row) {
>  break;
> }
> foreach ($nit as $row) {
>   // continues same iteration
> }
>
> >
> > Also, manually writing an iterator is quite painful.
> >
> > I sometimes implement "readers" that can be used like this (*):
> >
> > // Gets a reader at position zero.
> > $reader = $readerProvider->getReader();
> > while (FALSE !== $value = $reader->read()) {
> >   [..]
> > }
> >
> > (*) Note that I am using FALSE as an equivalent for "end of data". Of
> > course it would be nice if we had a dedicated constant for this, that
> > does not constrain the range of possible values of the iterator.
>
> That distinction is the reason why next() and valid() are different
> methods in iterators.


Not really, Iterator::next() returns void, so could as well return bool.

Regards, Niklas

Reply via email to