PHP 7.1.0 Release Candidate 5 Released


(PHP 5 >= 5.5.0, PHP 7)

Generator::rewindRewind the iterator


public void Generator::rewind ( void )

If iteration has already begun, this will throw an exception.


This function has no parameters.

Return Values

No value is returned.

add a note add a note

User Contributed Notes 2 notes

i'm pati on stackoverflow
6 months ago
Actually, this method can be useful to test a generator before iterating, as it executes your function up to the first yield statement. I.e. if you try to read a non-existent file in a generator, an error will normally occur only in client code foreach()'s first iteration. Sometimes this can be critical to check beforehand.

Take a look at a modified example from here:


function getLines($file) {
$f = fopen($file, 'r');
    try {
        while (
$line = fgets($f)) {
    } finally {

$getLines = getLines('no_such_file.txt');
$getLines->rewind(); // with ->rewind(), a file read error will be thrown here and a log file will not be cleared


foreach (
$getLines as $n => $line) { // without ->rewind(), the script will die here and your log file will be cleared
writeToLogFile('reading: ' . $line . "\n");



P.S.: When you iterate over a generator after ->rewind(), you'll get the first yielded value immediately, as the preceding code was already executed.
uther at somewherebetweennowhere dot net
1 year ago
I'm guessing the *only* purpose for this even existing is so that it is compatible with the Iterator interface o_O
To Top