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

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.

主站蜘蛛池模板: 通城县| 鱼台县| 房山区| 托克逊县| 南充市| 晋城| 盐城市| 瑞昌市| 常宁市| 喜德县| 多伦县| 洪洞县| 七台河市| 阿拉善右旗| 建水县| 罗田县| 常山县| 明星| 镇康县| 桐乡市| 绥江县| 襄樊市| 玉门市| 永新县| 醴陵市| 武强县| 茶陵县| 淄博市| 夏河县| 额敏县| 丰都县| 大田县| 襄汾县| 木兰县| 荔浦县| 孝昌县| 突泉县| 临沧市| 孙吴县| 阿克陶县| 革吉县|