#PHP#Laravel ORM#Generators#yield#Iterrators#LazyCollection

Generator


Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

生成器 (Generator) 提供了一個簡單的方法實現迭代器 (Iterrators),讓你能在 foreach 時能迭代使用資料而非都將資料存在記憶體 (Memory) 造成記憶體不足的窘境。

只要包含 yield 關鍵字的 function 一律都為生成器 (Generator)。

yield


The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.

yield 語句很像 return,但不同的點是 yield 不是 function 的終止與返回,而是回傳後暫停,下次讀取時再執行到下一個 yield 回傳,直到 function 內沒有 yield

<?php

function yieldDemo(): \Generator
{
    for ($i = 0; $i < 3; $i++) {
        yield $i;
    }
    yield 'A';
    yield 'B';
    yield 'C';
}

foreach (yieldDemo() as $val) {
    echo $val;
}

// output 012ABC