The role of php yield

不言
Release: 2023-03-25 06:34:02
Original
4563 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.'
'; }
Copy after login

  1. ##first Call the

    createRange function, passing in the parameter10, but thefor value is executed once and then stops, and tellsforeach that the first loop can be used value.

  2. ##foreach Start pairing$result Loop, come in firstsleep(1), and then start using a value given byfor 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. Sincesleep(1) inforeach, thefor 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!