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

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.

主站蜘蛛池模板: 西安市| 陵川县| 洮南市| 如皋市| 南京市| 安丘市| 福海县| 林西县| 会昌县| 城口县| 旌德县| 天津市| 湖口县| 旬阳县| 积石山| 漠河县| 密山市| 滁州市| 应城市| 拜城县| 弋阳县| 临汾市| 年辖:市辖区| 防城港市| 富蕴县| 泌阳县| 巢湖市| 江永县| 大兴区| 五莲县| 金湖县| 永福县| 禄丰县| 体育| 诸暨市| 竹山县| 安福县| 望奎县| 清水县| 临桂县| 施秉县|