- Building RESTful Web Services with PHP 7
- Haafiz Waheed ud din Ahmad
- 309字
- 2021-07-03 00:02:23
What are generators?
As stated in the PHP manual:
OK, here is a more detailed and easy-to-understand definition from the same source, php.net:
For example, you can simply write a function returning a lot of different numbers or values. But, the problem is that if a lot of different values means millions of values, then making and returning an array with those values is not efficient, because it will consume a lot of memory. So in that case, using generator makes more sense.
To understand, see this example:
/* function to return generator */
function getValues($max){
for($i=0; $i<$max; $i++ ){
yield $i*2;
}
}
// Using generator
foreach(getValues(99999) as $value){
echo "Values: $value <br>";
}
As you can see, there is a yield statement in code. It is just like the return statement but in generator, yield does not return all the values at once. It only returns a value every time yield executes, and yield is called only when the generator function is called. Also, every time yield executes, it resumes the code execution from where it was stopped the last time.
Now we have an understanding of generators, so let's look into the PHP7 features related to generators.
- SPSS數(shù)據(jù)挖掘與案例分析應(yīng)用實(shí)踐
- Node.js+Webpack開發(fā)實(shí)戰(zhàn)
- 零基礎(chǔ)PHP學(xué)習(xí)筆記
- 測(cè)試驅(qū)動(dòng)開發(fā):入門、實(shí)戰(zhàn)與進(jìn)階
- 簡(jiǎn)單高效LATEX
- Ext JS Data-driven Application Design
- Koa開發(fā):入門、進(jìn)階與實(shí)戰(zhàn)
- 微信小程序開發(fā)解析
- SQL基礎(chǔ)教程(視頻教學(xué)版)
- Python面向?qū)ο缶幊蹋簶?gòu)建游戲和GUI
- jQuery Mobile移動(dòng)應(yīng)用開發(fā)實(shí)戰(zhàn)(第3版)
- Microsoft Azure Storage Essentials
- Mastering Git
- Instant PHP Web Scraping
- Java程序設(shè)計(jì)教程