Using yield in callback?

半腔热情 提交于 2019-12-11 03:27:03

问题


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

回答1:


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.




回答2:


you can improvise an callback ! i did it with an array of object(Generator) and array_map

<?php

function pushyield($p){
    yield $p;
}

$tt[]=pushyield(1);
$tt[]=pushyield(10);
$tt[]=pushyield(100);





function parse($n)
{
//var_dump($n);echo('<hr style="width:30px;">');
   foreach($n as $ln) echo $ln.'<br>';
}


$b = array_map("parse", $tt);

?>


来源:https://stackoverflow.com/questions/29744661/using-yield-in-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!