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

Generator::send

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

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

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

generator.send.php

Generator::send

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

Generator::sendИспрати вредност до генераторот

= NULL

public Generator::send(mixed $value): mixed

Ја испраќа дадената вредност до генераторот како резултат на тековниот yield израз и го продолжува извршувањето на генераторот.

Ако генераторот не е на yield израз кога ќе се повика овој метод, прво ќе му се дозволи да напредува до првиот yield израз пред да ја испрати вредноста. Како такво, не е неопходно да се „прихранат“ PHP генераторите со Generator::next() повик (како што се прави во Python).

Параметри

value

Вредност што треба да се испрати во генераторот. Оваа вредност ќе биде вратена вредност од yield израз на кој генераторот моментално се наоѓа.

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

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

Примери

Пример #1 Користење Generator::send() за внесување вредности

<?php
function printer() {
echo
"I'm printer!".PHP_EOL;
while (
true) {
$string = yield;
echo
$string.PHP_EOL;
}
}

$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

I'm printer!
Hello world!
Bye world!

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

sfroelich01 at sp dot gm dot ail dot am dot com
12 години пред
Reading the example, it is a bit difficult to understand what exactly to do with this. The example below is a simple example of what you can do this.

<?php
function nums() {
    for ($i = 0; $i < 5; ++$i) {
                //get a value from the caller
        $cmd = (yield $i);
        
        if($cmd == 'stop')
            return;//exit the function
        }     
}

$gen = nums();
foreach($gen as $v)
{
    if($v == 3)//we are satisfied
        $gen->send('stop');
    
    echo "{$v}\n";
}

//Output
0
1
2
3
?>
php at didatus dot de
пред 4 години
If you want to use generator::send() within a foreach loop, you will most likely get an unexpected result. The Generator::send() method resumes the generator, which means the pointer within the generator is moved to the next element in the generator list.

Here is an example:

<?php

class ApiDummy
{
    private static $apiDummyData = ['a', 'b', 'c', 'd', 'e'];

    public static function getAll(): Generator {
        foreach (self::$apiDummyData as $entry) {
            echo 'yielding $elem' . PHP_EOL;
            $newElem = (yield $entry);
            echo 'yield return: ' . $newElem . PHP_EOL;
        }
    }
}

$generator = ApiDummy::getAll();

// example iteration one with unexpected result
foreach ($generator as $elem) {
    echo 'value from generator: ' . $elem . PHP_EOL;
    $generator->send($elem . '+');
}

// example iteration two with the expected result
while ($generator->valid()) {
    $elem = $generator->current();
    echo 'value from generator: ' . $elem . PHP_EOL;
    $generator->send($elem . '+');
}
?>

The result of example iteration one:
yielding $elem
value from generator: a
yield return: a+
yielding $elem
yield return:
yielding $elem
value from generator: c
yield return: c+
yielding $elem
yield return:
yielding $elem
value from generator: e
yield return: e+

As you can see, the values b and d are not printed out and also not extended by the + sign.
The foreach loop receives the first yield and the send call causes a second yield within the first loop. Therefor the second loop already receives the third yield and so on.

To avoid this, one solution could be to use a while loop and the Generator::send() method to move the generator cursor forward and the Generator::current() method to retrieve the current value. The loop can be controlled with the Generator::valid() method which returns false, if the generator has finished. See example iterator two. 

The expected result of example iteration two:
yielding $elem
value from generator: a
yield return: a+
yielding $elem
value from generator: b
yield return: b+
yielding $elem
value from generator: c
yield return: c+
yielding $elem
value from generator: d
yield return: d+
yielding $elem
value from generator: e
yield return: e+
— Поднесува задача до специфичен работник за извршување
пред 6 години
As of 7.3, the behavior of a generator in a foreach loop depends on whether or not it expects to receive data. Relevant if you are experiencing "skips".

<?php
class X implements IteratorAggregate {
    public function getIterator(){
        yield from [1,2,3,4,5];
    }
    public function getGenerator(){
        foreach ($this as $j => $each){
            echo "getGenerator(): yielding: {$j} => {$each}\n";
            $val = (yield $j => $each);
            yield; // ignore foreach's next()
            echo "getGenerator(): received: {$j} => {$val}\n";
        }
    }
}
$x = new X;

foreach ($x as $i => $val){
    echo "getIterator(): {$i} => {$val}\n";
}
echo "\n";

$gen = $x->getGenerator();
foreach ($gen as $j => $val){
    echo "getGenerator(): sending:  {$j} => {$val}\n";
    $gen->send($val);
}
?>

getIterator(): 0 => 1
getIterator(): 1 => 2
getIterator(): 2 => 3
getIterator(): 3 => 4
getIterator(): 4 => 5

getGenerator(): yielding: 0 => 1
getGenerator(): sending:  0 => 1
getGenerator(): received: 0 => 1
getGenerator(): yielding: 1 => 2
getGenerator(): sending:  1 => 2
getGenerator(): received: 1 => 2
getGenerator(): yielding: 2 => 3
getGenerator(): sending:  2 => 3
getGenerator(): received: 2 => 3
getGenerator(): yielding: 3 => 4
getGenerator(): sending:  3 => 4
getGenerator(): received: 3 => 4
getGenerator(): yielding: 4 => 5
getGenerator(): sending:  4 => 5
getGenerator(): received: 4 => 5
Glen
12 години пред
<?php
function foo() {
    $string = yield;
    echo $string;
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }
}

$generator = foo();
$generator->send('Hello world!');
foreach ($generator as $value) echo "$value\n";
?>

This code falls with the error:
PHP Fatal error:  Uncaught exception 'Exception' with message 'Cannot rewind a generator that was already run'.
foreach internally calls rewind, you should remember this!
На оваа страница

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

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

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

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

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