Yield is from the beginning of PHP5.5, about the yidle of the description of the bird Brother's blog To do a detailed explanation, I think it is a bit complicated, in the read a few other posts there are cases, I probably know that the role of yield is in doing a lot of data cycle processing, can save a large part of memory ~
Official: http://php.net/manual/zh/language.generators.syntax.php
Brother Bird: http://www.laruence.com/2015/05/28/3038.html
Reference cases illustrate the role of yield
<?PHP//code for Normal modefunction Generatedata ($max) {$arr= []; for($i =0; $i <= $max; $i + +) {$arr []=$i;}} Echo'pre-start memory consumption:'. Memory_get_usage (). Php_eol; $data= Generatedata (100000); Echo'memory consumption after generating array:'. Memory_get_usage (). Php_eol;unset ($data); Echo'memory consumption after release:'. Memory_get_usage (). Php_eol;
yield . Before PHP starts memory consumption: 387600 memory consumption after generating array: 387632 memory consumption after release: 387632
The memory difference used before and after is: 387632-387600 = 32
yield . Before PHP starts memory consumption: 386912 memory consumption after generating array: 387520 memory consumption after release: 386944
The memory difference used before and after is: 387520-386912 = 608
Obviously 608 is far greater than 32, not to say that it is to reduce memory utilization. Then adjust the value of the loop to try it. Change 100000 to 10000000
Use the CLI mode again to find out that the yield will be an error.
PHP Fatal Error: 134217728134217736 in/data/wwwroot/default7
But yield is still 608, because it is itself, and it produces real data when you iterate.
So if your data source is very large, then use yield. If the data source is small, of course you choose to load the memory once.
Get a quick look at the PHP iteration Builder yield