Generator::rewind
(PHP 5 >= 5.5.0, PHP 7)
Generator::rewind — Rewind the iterator
Описание
public void Generator::rewind
( void
)
If iteration has already begun, this will throw an exception.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Эта функция не возвращает значения после выполнения.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник языка
- Встроенные интерфейсы и классы
- Функция Generator::current() - Get the yielded value
- Generator::getReturn
- Функция Generator::key() - Get the yielded key
- Функция Generator::next() - Resume execution of the generator
- Функция Generator::rewind() - Rewind the iterator
- Функция Generator::send() - Send a value to the generator
- Функция Generator::throw() - Throw an exception into the generator
- Функция Generator::valid() - Check if the iterator has been closed
- Функция Generator::__wakeup() - Serialize callback
Коментарии
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:
http://php.net/manual/ru/language.generators.overview.php#112985
<?php
function getLines($file) {
$f = fopen($file, 'r');
try {
while ($line = fgets($f)) {
yield $line;
}
} finally {
fclose($f);
}
}
$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
openAndClearLogFile();
foreach ($getLines as $n => $line) { // without ->rewind(), the script will die here and your log file will be cleared
writeToLogFile('reading: ' . $line . "\n");
}
closeLogFile();
?>
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.