php 技术 yield 问题

function gen() {
    $ret= (yield'yield1');
    $ret= (yield'yield2');
}
 
$gen= gen();
 

var_dump($gen->send('ret1')); //输出是 yield2  不理解为什么

 

 

 

 

<?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();

var_dump( $gen->current());// 0 
$gen->next();
var_dump( $gen->current());// 1
$gen->next();

$gen->rewind(); // 我以为这里 会将指针 回归到 0 可是报错

PHP Fatal error:  Uncaught exception 'Exception' with message 'Cannot rewind a generator that was already run' in /var/www/html/learn.php:28
Stack trace:
#0 /var/www/html/ams/learn.php(28): Generator->rewind()
#1 {main}
  thrown in /var/www/html/ams/learn.php on line 28

 

 

var_dump( $gen->current());// 我以为会输出 0 

posted @ 2020-01-15 18:51  星云惊蛰  阅读(304)  评论(0)    收藏  举报