Generator::send

(PHP 5 >= 5.5.0, PHP 7)

Generator::send向生成器中传入一个值

说明

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

向生成器中传入一个值,并且当做 yield 表达式的结果,然后继续执行生成器。

如果当这个方法被调用时,生成器不在 yield 表达式,那么在传入值之前,它会先运行到第一个 yield 表达式。As such it is not necessary to "prime" PHP generators with a Generator::next() call (like it is done in Python).

参数

value

传入生成器的值。这个值将会被作为生成器当前所在的 yield 的返回值

返回值

返回生成的值。

范例

Example #1 用 Generator::send() 向生成器函数中传值

<?php
function printer() {
    while (
true) {
        
$string = yield;
        echo 
$string;
    }
}

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

以上例程会输出:

Hello world!

User Contributed Notes

baohx2000 at gmail dot com 24-Oct-2019 07:15
I have found that inverse generators (using $x = yield) is a great way to handle chunked batch processing. As data is being iterated, once a specific count has been fed to the generator, it processes and resets the data. For example, you could do a batch mysql insert every 500 records.

Example (note the handling of null, which you would send to the generator to handle stragglers after the previous batch)

function importer()
{
  $max = 500;
  $items = [];
  while (true) {
    $item = yield;
    if ($item !== null) {
      $items[] = yield;
    }
    if ($item === null || count($items) >= $max) {
       // do batch operations
       $items = [];
    }
  }
}
anonymous at example dot com 21-Jun-2019 10:38
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
kexianbin at diyism dot com 29-Sep-2015 06:47
an example:

$coroutine=call_user_func(create_function('', <<<'fun_code'
    echo "inner 1:\n";
    $rtn=(yield 'yield1');
    echo 'inner 2:';var_export($rtn);echo "\n";
    $rtn=(yield 'yield2');
    echo 'inner 3:';var_export($rtn);echo "\n";
    $rtn=(yield 'yield3');
    echo 'inner 4:';var_export($rtn);echo "\n";
fun_code
));
echo ":outer 1\n";                                       // :outer 1
var_export($coroutine->current());echo ":outer 2\n";     // inner 1:, 'yield1':outer 2
var_export($coroutine->current());echo ":outer 3\n";     // 'yield1':outer 3
var_export($coroutine->next());echo ":outer 4\n";        // inner 2:NULL, NULL:outer 4
var_export($coroutine->current());echo ":outer 5\n";     // 'yield2':outer 5
var_export($coroutine->send('jack'));echo ":outer 6\n";  // inner 3:'jack', 'yield3':outer 6
var_export($coroutine->current());echo ":outer 7\n";     // 'yield3':outer 7
var_export($coroutine->send('peter'));echo ":outer 8\n"; // inner 4:'peter', NULL:outer 8
sergei dot solomonov at gmail dot com 08-Oct-2013 06:30
<?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!
sfroelich01 at sp dot gm dot ail dot am dot com 17-Jul-2013 12:11
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
?>