Intermediate LevelPHP 8+
How do you send data back into a running PHP Generator coroutine using $generator->send($val)?
❓ Interview Prompt: Explain two-way generator communication, yield as a receiver expression, $generator->send(), and coroutine state machines.
Generators in PHP are not just one-way data producers; they can also act as Coroutines that receive data dynamically from the caller via '$generator->send($val)'.
How Generator Coroutines Work:
1
In a generator function, assigning 'yield' to a variable ('$input = (yield)') causes the generator to pause and wait for input.
2
The calling script invokes '$generator->send("data")', which injects the value into '$input' and resumes execution until the next 'yield'!
Code Implementation Example
php
<?php
// Coroutine logger receiving data dynamically via yield
function loggerCoroutine(): Generator {
echo "Logger initialized.
";
while (true) {
// Pauses and waits for caller to inject value via send()!
$message = (yield);
echo "[LOGGED] {$message}
";
}
}
$logger = loggerCoroutine();
$logger->current(); // Initialize generator to first yield
$logger->send("First log entry"); // Outputs: [LOGGED] First log entry
$logger->send("Second log entry"); // Outputs: [LOGGED] Second log entry💡Injecting values into a PHP Generator coroutine using $generator->send().
🎯 Interview Key Takeaway
$generator->send($val) injects values into a paused yield expression, enabling two-way coroutine communication.
#Generators#Coroutines#send#Intermediate
Back to all PHP 8+ Questions→