Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a generator method within a class

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";
};
like image 462
jamima Avatar asked May 18 '26 13:05

jamima


1 Answers

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;
    }

}
like image 125
user3942918 Avatar answered May 20 '26 04:05

user3942918