In PHP, the yield
keyword is used within a generator function to create an iterator. It allows the function to "pause" and "resume" execution while returning a value to the calling code each time it is called. This makes yield
particularly useful for handling large datasets or streams of data in a memory-efficient way, as it produces values one at a time without having to load the entire dataset into memory.
How yield
Works in a Generator
A generator in PHP is a function that uses yield
to return values in a sequence. When a generator function is called, it returns an object of type Generator
instead of executing its code. You can then iterate over this generator object, and each time yield
is encountered, it "yields" a value back to the loop, pauses, and retains its state. When the loop requests the next value, the function resumes execution from the last yield
.
Example of yield
in a Generator Function
Here’s a simple example to demonstrate how yield
works:
function myGenerator() {
yield 1; // First yield
yield 2; // Second yield
yield 3; // Third yield
}
$gen = myGenerator();
foreach ($gen as $value) {
echo $value . "\n"; // Output will be 1, 2, 3 on separate lines
}
In this example:
- The
myGenerator
function defines threeyield
statements. - When called,
myGenerator
doesn’t run immediately; instead, it returns aGenerator
object. - The
foreach
loop starts iterating over$gen
. - Each time the loop runs, the generator function executes up to the next
yield
, returning the current value to$value
and pausing. - When the loop requests the next value, the function continues from where it left off until it reaches the next
yield
.
Why Use yield
?
Using yield
has several benefits, including:
-
Memory Efficiency:
yield
generates values one at a time, making it suitable for handling large data collections without loading them entirely into memory. -
Lazy Evaluation: Since it only computes values as needed, it is efficient for operations that don't require the entire dataset at once.
-
Maintain State Between Iterations: The generator retains its state across iterations, so it can track variables or context throughout the process.
Example of a Generator with a Loop
Generators are often used with loops to yield a series of values. Here’s a generator function that yields numbers up to a specified limit:
function numberGenerator($limit) {
for ($i = 1; $i <= $limit; $i++) {
yield $i; // Yield each number from 1 to $limit
}
}
$gen = numberGenerator(5);
foreach ($gen as $value) {
echo $value . "\n"; // Outputs 1, 2, 3, 4, 5 on separate lines
}
In this example:
- The generator only produces one number at a time, up to the specified limit, so it’s memory-efficient.
- The state of
$i
is maintained between each call.
Summary
The yield
keyword in PHP is essential for writing generator functions that produce values on demand without consuming excessive memory. It allows PHP functions to act as lazy iterators, enabling efficient data processing patterns.