Generator là hàm dùng yield để trả về nhiều giá trị từng cái một mà không cần tải tất cả vào bộ nhớ.
- Khai báo:
function numbers() { yield 1; yield 2; yield 3; }rồi lặp vớiforeach(numbers() as $num). - Tiết kiệm bộ nhớ cho dataset lớn: xử lý file với
yieldđọc từng dòng thay vì tải toàn bộ file. - Dùng
yield $key => $valuecho cặp key-value. - Generator chậm hơn cho dataset nhỏ nhưng không thể thiếu khi xử lý file lớn, streams hay chuỗi vô hạn.
Generators are functions that use yield to return multiple values one at a time without loading all into memory.
- Define with
function numbers() { yield 1; yield 2; yield 3; }then iterate withforeach(numbers() as $num). - Memory-efficient for large datasets: processing a file with
yieldreads one line at a time instead of loading entire file. - Use
yield $key => $valuefor key-value pairs. - Generators are slower for small datasets but essential for processing large files, streams, or infinite sequences.