I have a method within a class that yields a couple of values. When calling the parent::generator_function() the values are not yielded. How yield them
class Papa
{
public function generator_function()
{
yield 1;
yield 2;
yield 3;
}
}
class Child extends Papa
{
public function generator_function()
{
parent::generator_function();
yield 4;
}
}
$child = new Child();
foreach ($child->generator_function() as $value) {
echo "$value\n";
};
Simply calling parent::generator_function() gives you a generator, which you're doing nothing with. Within a generator you can delegate to another generator via yield from.
In PHP 7, generator delegation allows you to yield values from another generator, Traversable object, or array by using the yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.
E.g.:
class Child extends Papa
{
public function generator_function()
{
yield from parent::generator_function();
yield 4;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With