2017-04-24 167 views
3

在PHP 7.1中有一個新的iterable psudo類型,它抽象出數組和Traversable對象。PHP - 迭代兩次泛型迭代

假設在我的代碼我有一類這樣的:

class Foo 
{ 
    private $iterable; 

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

    public function firstMethod() 
    { 
     foreach ($this->iterable as $item) {...} 
    } 

    public function secondMethod() 
    { 
     foreach ($this->iterable as $item) {...} 
    } 
} 

能正常工作是$iterable是一個數組或Iterator,除非$iterableGenerator。在這種情況下,實際上,撥打firstMethod()然後secondMethod()將產生以下Exception: Cannot traverse an already closed generator

有沒有辦法避免這個問題?

回答

2

發電機不能倒帶。如果你想避免這個問題,你必須建立一個新的發電機。這可以,如果你創建一個實現IteratorAggregate對象可以自動完成:

class Iter implements IteratorAggregate 
{ 
    public function getIterator() 
    { 
     foreach ([1, 2, 3, 4, 5] as $i) { 
      yield $i; 
     } 
    } 
} 

然後,只需通過這個對象作爲你的迭代器的實例:

$iter = new Iter(); 
$foo = new Foo($iter); 
$foo->firstMethod(); 
$foo->secondMethod(); 

輸出:

1 
2 
3 
4 
5 
1 
2 
3 
4 
5