生成器委托

PHP7中支持delegating generator,可以自动展开subgenerator;

A “subgenerator” is a Generator used in the portion of the yield from syntax.

我们需要在PHP5支持子生成器,将子生成器最后yield值作为父生成器yield表达式结果,仅只需要加两行代码,递归的产生一个AsyncTask对象来执行子生成器即可。

  1. <?php
  2. final class AsyncTask
  3. {
  4. public function next($result = null)
  5. {
  6. $value = $this->gen->send($result);
  7. if ($this->gen->valid()) {
  8. if ($value instanceof \Generator) {
  9. $value = (new self($value))->begin();
  10. }
  11. return $this->next($value);
  12. } else {
  13. return $result;
  14. }
  15. }
  16. }
  1. <?php
  2. function newSubGen()
  3. {
  4. yield 0;
  5. yield 1;
  6. }
  7. function newGen()
  8. {
  9. $r1 = (yield newSubGen());
  10. $r2 = (yield 2);
  11. echo $r1, $r2;
  12. yield 3;
  13. }
  14. $task = new AsyncTask(newGen());
  15. $r = $task->begin(); // output: 12
  16. echo $r; // output: 3