function* powGenerator() { var result = Math.pow(yield "a",yield "b"); return result; } var g = powGenerator(); console.log(g.next().value); // "a",from the first yield console.log(g.next(10).value); // "b",from the second console.log(g.next(2).value); // 100,the result
我正在尝试使用类似于PHP的模型,但这有点令人头疼.
<?PHP function powGenerator() { return pow((yield 'a'),(yield 'b')); }
Fatal error: Generators cannot return values using “return”
好吧,也许我会用另一个产量来获得最终价值? …
<?PHP function powGenerator() { yield pow((yield 'a'),(yield 'b')); } $g = powGenerator(); //=> Generator {#180} echo $g->send(10); //=> "b" echo $g->send(2); //=> 100
好的,所以我恢复了价值,但这里有两个主要问题
>我的“a”去了哪里? – 注意在JS示例中,我能够访问“a”和“b”产生的值以及100个最终结果.
>发电机还没有完成! – 我必须拨打额外的时间来完成发电机
$g->valid(); //=> true $g->send('?'); //=> null $g->valid(); //=> false
public mixed Generator::send ( mixed $value )
Sends the given value to the generator as the result of the current
yield
expression and resumes execution of the generator.If the generator is not at a
yield
expression when this method is called,it will first be let to advance to the firstyield
expression before sending the value. As such it is not necessary to “prime” PHP generators with a 07002 call (like it is done in Python).
强调“因此没有必要使用Generator :: next()来”启动“PHP生成器”.好的,但这究竟意味着什么?我没有像JavaScript示例那样“填充”它,但是第一个产生的值也被吞噬了.
任何人都可以解释你是如何在不使用foreach的情况下逐步完成生成器的吗?
$g = powGenerator(); echo $g->current(); //a
你然后两次发送值并恢复执行,$g-> valid()在此之后为真,因为你没有在第三次收益后恢复 – 发电机不完整而且可能还有更多要做的事情.考虑:
function powGenerator() { yield pow((yield 'a'),(yield 'b')); echo "Okay,finishing here now!\n"; } $g = powGenerator(); echo $g->current(),"\n"; //a echo $g->send(10),"\n"; //b echo $g->send(2),"\n"; //100 $g->next(); // Resumes execution of the generator,// which prints its own message and completes. var_dump($g->valid()); //false
这个’输出:
a b 100 Okay,finishing here now! bool(false)
现在在PHP 7中你可以return from a generator.
function powGenerator() { return pow((yield 'a'),(yield 'b')); echo "This will never print."; } $g = powGenerator(); echo $g->current(),"\n"; // Prints just the newline,you're moving on // to a return which you must get explicitly. var_dump($g->valid()); // Generator complete,you're free to get the return. echo $g->getReturn(),"\n";
哪个输出:
a b bool(false) 100
至于在没有foreach的情况下单步执行它们 – Generator实现了Iterator,所以它有适当的方法来处理它:current,key,next,rewind和valid.有一点需要注意,如果你调用它,它将引发异常已经开始的发电机.
这样做的一个例子也演示了PHP 7的新generator delegation:
function letterGenerator() { yield from range('a','z'); } $g = letterGenerator(); while ($g->valid()) { echo $g->current(); $g->next(); }
输出:
abcdefghijklmnopqrstuvwxyz