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

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.

主站蜘蛛池模板: 兰溪市| 黎平县| 孝义市| 金阳县| 漳州市| 合江县| 石河子市| 阜宁县| 洱源县| 金塔县| 山西省| 连州市| 陕西省| 名山县| 平罗县| 大港区| 云梦县| 盖州市| 沭阳县| 宁国市| 大连市| 南和县| 大同市| 隆子县| 广安市| 德兴市| 盘山县| 赤水市| 宁阳县| 温宿县| 孝感市| 嘉荫县| 安阳县| 南涧| 化州市| 邳州市| 定西市| 慈溪市| 平利县| 锦州市| 保靖县|