The usage of yield in php, I believe that most people still don’t know how to use it, or even don’t know what yield is, so this article I am here to tell you some issues about yield and how to use yield to solve the problems we encounter in Php.
Solve the bottleneck of running memory. The variables in the PHP program are stored in the memory. When reading Excel files, there will be insufficient memory and the following will appear:
Fatal Error: Allowed memory size of xxxxxx bytes
So the maximum running memory setting of php will be set: ini_set('memory_limit', '200M')
But when we read a file as large as 5g At that time, we may not be able to bear the running memory, so we will choose yield
to run:
<?phpfunction 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:
<?phpfunction 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 memory. , but consumed one by one.
Create a txt file and write:
第1行 第2行 第3行 第4行 第5行 第6行 第7行 第8行
<?phpfunction 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
Recommended study: "PHP Video Tutorial"
The above is the detailed content of Learn how to use yield in php in one minute (share). For more information, please follow other related articles on the PHP Chinese website!