官术网_书友最值得收藏!

What are generators?

As stated in the PHP manual:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the iterator interface.

OK, here is a more detailed and easy-to-understand definition from the same source, php.net:

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

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.

主站蜘蛛池模板: 额敏县| 永顺县| 宜都市| 视频| 铜鼓县| 荆州市| 河南省| 辉南县| 锦州市| 乌拉特前旗| 玉环县| 二连浩特市| 万全县| 淳化县| 巨野县| 宣化县| 牟定县| 静安区| 松滋市| 萨嘎县| 杭州市| 麻城市| 出国| 山东省| 贡觉县| 汝城县| 巴马| 长泰县| 衡阳市| 云安县| 丹凤县| 新绛县| 郸城县| 永德县| 三穗县| 蓬安县| 勐海县| 遂溪县| 钟祥市| 芜湖县| 临桂县|