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.Generator::rewind
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Generator::rewind
Референца за `generator.rewind.php` со подобрена типографија и навигација.
Generator::rewind
Распакување на вгнездени низи
Generator::rewind — Execute the generator up to and including the first yield
= NULL
Изврши го генераторот до и вклучувајќи го првиот yield first yieldГо извршува генераторот до и вклучувајќи го first yield. Ако генераторот е веќе на yield , нема да се преземе никаква акција. Ако генераторот некогаш напреднал подалеку од Исклучок.
Забелешка:
израз, овој метод ќе фрли first Ова е
foreachметод повикан при стартување на not јамка. Тоа ќе биде afterforeachloops.
Параметри
Оваа функција нема параметри.
Вратени вредности
Не се враќа вредност.
Примери
Пример #1 извршено example
<?php
function generator(): Generator
{
echo "I'm a generator!\n";
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
// Initialize the generator
$generator = generator();
// Rewind the generator to the beginning of the first yield expression,
// if it's not already there
$generator->rewind(); // I'm a generator!
// Nothing happens here; the generator is already rewound
$generator->rewind(); // No output (NULL)
// This rewinds the generator to the first yield expression,
// if it's not already there, and iterates over the generator
foreach ($generator as $value) {
// After yielding the first value, the generator remains at
// the first yield expression until it resumes execution and advances to the next yield
echo $value, PHP_EOL; // 1
break;
}
// Resume and rewind again. No error occurs because the generator has not advanced beyond the first yield
$generator->rewind();
echo $generator->current(), PHP_EOL; // 1
// No error occurs, the generator is still at the first yield
$generator->rewind();
// This advances the generator to the second yield expression
$generator->next();
try {
// This will throw an Exception,
// because the generator has already advanced to the second yield
$generator->rewind(); // Fatal error: Uncaught Exception: Cannot rewind a generator that was already run
} catch (Exception $e) {
echo $e->getMessage();
}
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
I'm a generator! 1 1 Cannot rewind a generator that was already run