Implementing an iterator

This chapter describe how an iterator should be implemented

variables

To easier maintainers work, some iterator variables should have the same name in all iterators.

boolean _end

boolean $_end : (default is false)

This variable is a flag that will be set to true when the end of the iteration is reached.

int _index

int $_index : (default is -1)

This variable contains the current item index in source data (0 to number of items -1).

Ref _value

Ref $_value : (default is null)

This is the reference to current item value (see Ref class and reference documentation).

In Types iterators, Ref is used to store current item value, this is a way to ensure, data retrieved using value() method won't be overwriten by a next() call. This also help keeping references up to date.

Ref _src

Ref $_src   : (default is null)

This member stores a reference to data source.

constructor

The iterator is returned by an iterable object, it most common argument will be the source object.

After referencing the source object, the iterator must reset itself to prepare iteration.

Except for this two points, the constructor behaviour is defined by the developper, depending on the data type.

method reset

If the source data is empty, the _end flag must be set to true and the reset will return.

If the iterator is a once only iterator and the iterator already started (_index != -1), this method should throw an exception (ResetError).

The internal iterator _index must be reset to 0 and _value must be set to the first item.

method isValid

This method returns the value of 'not _end' (!$this->_end)

Any other behavious is useless and will confuse maintainers.

method next

If _end is set to true, this method do nothing.

This method advance the iterator index.

If the index is out of source bounds, the _end flag is set to true and the next() method ends.

Then this method retrieve a reference to the current item an store it in _value.

This method ends, returning _value content as a reference

method value

This method throws an exception if the iterator reached its end.

It returns the current value by reference otherwise.

method index

This method returns current iterator index (_index).

method key (optional)

This method returns the current iterator key for associative resource iterators.

By default, this method returns index() value.

method remove (optional/dangerous)

This method ask source object to remove current iterator item.

See Removable iterators for a discussion about this method behaviour.