Home  >  Article  >  Backend Development  >  Introduction to yield communication function loops inside and outside (code example)

Introduction to yield communication function loops inside and outside (code example)

不言
不言forward
2019-03-02 09:44:391640browse

This article brings you an introduction (code example) inside and outside the yield communication function loop. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Yield is used for communication inside and outside the function, and inside and outside the loop. When your function needs to return a large array, you need to traverse the large array during the loop, and you need to traverse the function multiple times. Return value, this is useful

2. When I only need to process everything in one loop, this is nothing

<?php
$start=memory_get_usage();
function readTxt(){
    $handle = fopen("./2018-12-awk-uniq.txt", &#39;rb&#39;);
    while (feof($handle)===false) {
        yield fgets($handle);
        echo "\n4:***************\n";
    }  
    fclose($handle);
}
foreach (readTxt() as $key => $value) {
        echo "1:".$value;
        echo "2:=================\n";
        echo "3:".(memory_get_usage()-$start);
}

When looping within the function, I will pause and return to my outer loop. Pay attention to the order of the output.

Of course, if I am in a loop that reads a row of data, all the work will be done. After everything is done, this yield is no longer needed and serves a passing function

The above is the detailed content of Introduction to yield communication function loops inside and outside (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete