略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Generator::rewind

2024-04-29

Generator::rewind

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::rewind重置迭代器

说明

public Generator::rewind(): void

如果迭代已经开始了,这里会抛出一个异常。

参数

此函数没有参数。

返回值

没有返回值。

add a noteadd a note

User Contributed Notes 2 notes

up
15
i'm pati on stackoverflow
6 years 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:
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.
up
-16
uther at somewherebetweennowhere dot net
6 years ago
I'm guessing the *only* purpose for this even existing is so that it is compatible with the Iterator interface o_O

官方地址:https://www.php.net/manual/en/generator.rewind.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3