An iterator cannot be used with foreach by reference

Description

It is posssible to use a foreach loop with a reference on the blind variable: this allows the original data to be modified.

Such feature is possible with an array as a source, but it is not possible with an iterator as a source. The iterator allows reading, but has no support for writing the individual elements it emits.

Example

<?php

    $heap = new SplMinHeap;
    foreach( $heap as &$item ) {}

?>

Solutions

  • Turn the iterator into an array and use it.

  • Keep the blind variable per-value, and call a setter in it to update it.

  • Use objects in the iterator, it is possible to update the blind variable without the reference.