- 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.
- C語(yǔ)言程序設(shè)計(jì)案例教程(第2版)
- 小程序?qū)崙?zhàn)視頻課:微信小程序開發(fā)全案精講
- Elastic Stack應(yīng)用寶典
- Learning Laravel 4 Application Development
- Mastering RStudio:Develop,Communicate,and Collaborate with R
- Java EE 7 Performance Tuning and Optimization
- C/C++程序員面試指南
- Cybersecurity Attacks:Red Team Strategies
- PHP從入門到精通(第4版)(軟件開發(fā)視頻大講堂)
- Unity 3D/2D移動(dòng)開發(fā)實(shí)戰(zhàn)教程
- Mastering C++ Multithreading
- Clojure for Java Developers
- 從零開始學(xué)Android開發(fā)
- Java 從入門到項(xiàng)目實(shí)踐(超值版)
- Android編程權(quán)威指南(第4版)