Home > Article > Backend Development > What is the usage of yield in php
This article will introduce you to the usage of yield in php. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
I have heard before that there are coroutines in PHP, so I checked it out and learned about it.
Demo has been uploaded to my github notes
Solve the bottleneck of running memory. The variables in the PHP program are stored in the memory. I have encountered this before. When reading an Excel file, there will be insufficient memory, and an error message will appear:
Fatal Error: Allowed memory size of xxxxxx bytes
So the maximum running memory setting for php will be set: ini_set('memory_limit', '200M')
But when we read When fetching a file as large as 5g, we may not be able to handle the running memory, so we will choose yield
Run:
<?php function createRange($number){ $data = []; for($i=0;$i<$number;$i++){ $data[] = time(); } return $data; } $data =createRange(10); foreach($data as $value){ sleep(1);//这里停顿1秒,我们后续有用 echo $value.PHP_EOL; }
The time is the same. If yield is used:
<?php function createRange($number){ for($i=0;$i<$number;$i++){ yield time(); } } $data =createRange(10); foreach($data as $value){ sleep(1);//这里停顿1秒,我们后续有用 echo $value.PHP_EOL; }
The time interval is one second, so through the example of yield, we know that it is not like the first example to store the contents of the for loop in the memory , but consumed one by one.
Create a txt file and write:
第1行 第2行 第3行 第4行 第5行 第6行 第7行 第8行
<?php function readTxt() { # code... $handle = fopen("./test.txt", 'rb'); while (feof($handle)===false) { # code... yield fgets($handle); } fclose($handle); } foreach (readTxt() as $key => $value) { # code... sleep(1); echo $value; }
Use php to read the file, it is read line by line
At this point, you probably know the function of yield, and then we will go deeper.
Recommended learning: php video tutorial
The above is the detailed content of What is the usage of yield in php. For more information, please follow other related articles on the PHP Chinese website!