Advertisement
Intermediate PHP, Generators & Iterators

How can a generator receive values sent into it during iteration using the send method, enabling two way communication with the calling code?

Short answer

In addition to yielding values out to the calling code, a generator can also receive a value sent into it using the send method, which resumes the generator's execution and makes that sent value become the result of the current yield expression inside the generator, enabling…

Save PHP mock interview
Advertisement
AModel answer
In addition to yielding values out to the calling code, a generator can also receive a value sent into it using the send method, which resumes the generator's execution and makes that sent value become the result of the current yield expression inside the generator, enabling more advanced patterns where the generator's behavior can be influenced dynamically based on values provided by the code consuming it.
function echoTimes() {
    while (true) {
        $value = yield;
        echo "Received: $value\n";
    }
}
$gen = echoTimes();
$gen->current();
$gen->send('Hello');
Real-world example
A simple task processing generator receives commands sent into it by the calling code, using the sent values to determine what specific work to perform next, effectively acting like a lightweight coroutine within a single script.
Likely follow-ups
  • What is the difference between yield used as an expression versus a statement?
  • How does this two way communication pattern relate to coroutines in languages that support them more natively?
Related topics