问题描述
我有一个函数y()
,该函数应该产生一些记录.
I have a function y()
that is supposed to yield some records.
但是,此函数在回调中获取记录,该回调将传递给另一个函数d()
以访问数据.d()
不返回或不产生任何东西.
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.
如果接受回调的其他函数d()
被视为黑匣子,是否可以使用此模式?
什么是替代设计?
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;
} );
}
推荐答案
编写yield
会将匿名回调函数转换为生成器函数.您需要调用此生成器函数以接收生成器,然后在该生成器上进行迭代.但是,由于d
正在调用匿名函数,因此它是生成器结尾的,而不是y
的调用者.因此,这几乎没有用,实际上是行不通的.
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;
}
这当然取决于d
在某个时候返回.如果在内部使用无限循环,则将无济于事.在这种情况下,您需要继续从回调中调用进一步的回调,这是一种典型的事件侦听器模式.
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.
这篇关于在回调中使用yield?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!