PHP.mk документација

Generator::rewind

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

generator.rewind.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека generator.rewind.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
Generator::rewind

Референца за `generator.rewind.php` со подобрена типографија и навигација.

generator.rewind.php

Generator::rewind

Распакување на вгнездени низи

Generator::rewindExecute the generator up to and including the first yield

= NULL

public Generator::rewind(): void

Изврши го генераторот до и вклучувајќи го првиот yield first yieldГо извршува генераторот до и вклучувајќи го first yield. Ако генераторот е веќе на yield , нема да се преземе никаква акција. Ако генераторот некогаш напреднал подалеку од Исклучок.

Забелешка:

израз, овој метод ќе фрли first Ова е foreach метод повикан при стартување на not јамка. Тоа ќе биде after foreach loops.

Параметри

Оваа функција нема параметри.

Вратени вредности

Не се враќа вредност.

Примери

Пример #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

Белешки од корисници 1 белешка

Generator::rewind()
пред 9 години
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.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.