You can create a generator in PHP that yields values:
function genOneTwoThree() {
foreach ([1,2,3] as $i => $number)
yield $i => $number;
}
Then you can consume them like:
foreach (genOneTwoThree() as $i) {
echo $i;
}
This "lvalue" usage is documented here: https://secure.php.net/manual/en/language.generators.syntax.php#control-structures.yield
But yield can also be used as an rvalue like this:
function printer() {
while (true) {
$string = yield;
echo $string;
}
}
$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
This "consumer" example is given in the "Generator" documentation at https://secure.php.net/manual/en/generator.send.php
Is there another place that actually documents this type of usage? Some other specific question I have are:
- Can rvalue yield functions return something, and when does that happen?
- What happens when rvalue yield functions affect global state
- Can you use rvalue and lvalue yield to filter a generator?