第一个产生的值并没有被吞噬,只是你从来没有看过它。
$g = powGenerator();
echo $g->current(); //a
然后您两次发送值并恢复执行,$g->valid()
is true
在此之后,因为你在第三次之后还没有恢复yield
- 生成器尚未完成,可能还有更多工作要做。考虑:
function powGenerator() {
yield pow((yield 'a'), (yield 'b'));
echo "Okay, finishing here now!\n";
}
$g = powGenerator();
echo $g->current(), "\n"; //a
echo $g->send(10), "\n"; //b
echo $g->send(2), "\n"; //100
$g->next(); // Resumes execution of the generator,
// which prints its own message and completes.
var_dump($g->valid()); //false
这将输出:
a
b
100
Okay, finishing here now!
bool(false)
现在在 PHP 7 中你can 从发电机返回 https://wiki.php.net/rfc/generator-return-expressions.
function powGenerator() {
return pow((yield 'a'), (yield 'b'));
echo "This will never print.";
}
$g = powGenerator();
echo $g->current(), "\n"; //a
echo $g->send(10), "\n"; //b
echo $g->send(2), "\n"; // Prints just the newline, you're moving on
// to a return which you must get explicitly.
var_dump($g->valid()); // Generator complete, you're free to get the return.
echo $g->getReturn(), "\n";
哪个输出:
a
b
bool(false)
100
至于在没有foreach
- 发电机 http://www.php.net/manual/en/class.generator.php实施Iterator http://php.net/manual/en/class.iterator.php,所以它有适当的方法来处理它:current http://php.net/manual/en/generator.current.php, key http://php.net/manual/en/generator.key.php, next http://php.net/manual/en/generator.next.php, rewind http://php.net/manual/en/generator.rewind.php, and valid http://php.net/manual/en/generator.valid.php。需要注意的是rewind
如果您在已经启动的生成器上调用它,将会抛出异常。
一个执行此操作并演示 PHP 7 新功能的示例生成器委托 https://wiki.php.net/rfc/generator-delegation:
function letterGenerator() {
yield from range('a', 'z');
}
$g = letterGenerator();
while ($g->valid()) {
echo $g->current();
$g->next();
}
Output:
abcdefghijklmnopqrstuvwxyz