Arc
Arc

Reputation: 11296

Using yield in callback?

I have a function y() that is supposed to yield some records.

This function however obtains the records within a callback which is passed to another function d() to access the data. d() does not return or yield anything.

Is this pattern possible if that other function d() that accepts the callback is considered a black box?
What would be an alternative design?

function y() {
    d( function ($records) { // May be called multiple times
        // How to yield for "y()"?
        foreach ($records as $record)
            yield $record;
    } );
}

Upvotes: 3

Views: 2919

Answers (1)

deceze
deceze

Reputation: 522382

Writing yield turns the anonymous callback function into a generator function. You'd need to call this generator function to receive a generator and then iterate over that generator. But since d is calling the anonymous function, it's the one that ends up with the generator, not the caller of y. So this is of little use and in fact does not work.

It seems the best you can do is this:

function y() {
    $results = [];
    d(function ($val) use (&$results) {
        $results[] = $val;
    });
    return $results;
}

foreach (y() as $val) {
    echo $val, PHP_EOL;
}

This of course depends on d returning at some point. If internally it uses an endless loop, this won't do any good. In that case you'd need to keep calling further callbacks from within your callback, which is a typical event listener pattern.

Upvotes: 2

Related Questions