如何限制生成器返回的结果?

时间:2019-04-23 20:21:49

标签: php generator

interface Yielder
{
   public function getData(): iterable;
}

class ClassicYielder implements Yielder
{
   public function getData(): iterable
   {
       yield 1;
       yield 2;
       yield 3;
       yield 4;
       yield 5;
   }
}

class LimitedYielder implements Yielder
{
   private $wrapped;

   private $total = 3;

   private $count = 0;

   public function __construct(Yielder $wrapped)
   {
       $this->wrapped = $wrapped;
   }

   public function getData(): iterable
   {
       if ($this->count < $this->total) {
          $this->count++;
          yield from $this->wrapped->getData();
       }

       // how to stop here?
   }
}

$x = new ClassicYielder();
$y = new LimitedYielder($x);

foreach ($y->getData() as $data) {
   echo $data;
}

===

Will print: 1 2 3 4 5

我有一个Yielder接口,它具有一个通过yield返回可迭代的单一方法。我想将我的经典yielder包装在一个有限的变量中,只要条件通过,它只会产生值。如您所见,上面的代码将产生我经典的yielder的所有值,而无需跟踪我的计数器。

我在这里做错了什么?有什么办法可以使它正常工作?

0 个答案:

没有答案