Em đang đọc sách PHP CookBook nhưng khi đọc tới đoạn này thì chưa hiểu ý của tác giả,mọi người có thể giúp em được không ạ:
"
Starting with PHP 5.5, you can use a generator to operate on a series. A generator is a
function that, instead of calling return to return a value, calls yield (perhaps within a
loop). Then a call to that function can be used where you’d otherwise use an array, and
you operate on the series of values passed to the yield keyword. For example, here’s
how to use a generator to produce a list of squares:Code:
function squares($start, $stop)
{
if ($start < $stop) {
for ($i = $start; $i <= $stop; $i++) {
yield $i => $i * $i;
}
}
else {
for ($i = $stop; $i >= $start; $i–) {
yield $i => $i * $i;
}
}
}
foreach (squares(3, 15) as $n => $square) {
printf("%d squared is %d\n", $n, $square);
}PHP keeps calling the squares() function as long as it calls yield. The key and value
passed to yield can be used in the foreach just like a regular array element.
Generators are handy because you can have arbitrary behavior to create each value
(whatever you put inside your function) but the values are generated on demand. You
don’t have to commit the memory (or processing) to create the whole array first, as with
range(), before you start operating on it."
Em xin chân thành cảm ơn