php群发不用foreach,如何在没有foreach的情况下使用PHP生成器?
第一個產生的價值沒有被吞噬,你只是從來沒有看過它.
$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)
function powGenerator() {
return pow((yield 'a'), (yield 'b'));
echo "This will never print.";
}
$g = powGenerator();
echo $g->current(), "\n"; //a
echo $g->send(10), "\n"; //b
echo $g->send(2), "\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
總結
以上是生活随笔為你收集整理的php群发不用foreach,如何在没有foreach的情况下使用PHP生成器?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php php5,初探 PHP5 (一)
- 下一篇: 动态规划算法php,php算法学习之动态