The role of php yield

不言
Release: 2023-03-25 06:34:02
Original
4653 people have browsed it

This article mainly introduces the role of php yield, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

function createRange($number){  
  for($i=0;$i<$number;$i++){
        yield time();
    }
}$result = createRange(10); // 这里调用上面我们创建的函数
foreach($result as $value){  
  sleep(1);  
    echo $value.&#39;<br />';
 }
Copy after login

  1. ##first Call the

    createRange function, passing in the parameter 10, but the for value is executed once and then stops, and tells foreach that the first loop can be used value.

  2. ##foreach Start pairing $result Loop, come in first sleep(1), and then start using a value given by for to perform output.

  3. #foreach preparation In the second loop, before starting the second loop, it makes another request to the

    for loop.

  4. The for loop is executed again and the generated timestamp is told

    foreach .

  5. foreach gets the second value and outputs it. Since sleep(1) in foreach, the for loop is delayed by 1 second to generate the current time

So, during the entire code execution, there is always only one record value participating in the loop, and there is only one piece of information in the memory.

No matter how big the $number is initially passed in, since not all result sets are generated immediately, the memory is always a loop of values.

Related recommendations:

In-depth understanding of static and yield keywords in php

Detailed introduction about yield

The above is the detailed content of The role of php yield. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template