Home > Article > Backend Development > Introduction to PHP iterator generators
This article mainly introduces the introduction of PHP iterator generator, which has certain reference value. Now I share it with you. Friends in need can refer to it
Iteration refers to executing a process repeatedly, and each execution is called an iteration. For example, ordinary traversal is iteration:
$arr = [1, 2, 3, 4, 5];foreach($arr as $key => $value) { echo $key . ' => ' . $value . "\n";}
We can see that foreach
traverses the array and iteratively outputs its contents. Inside foreach
, each iteration will assign the value of the current element to $value
and move the array pointer to the next element to prepare for the next iteration, thereby achieving sequence Traverse. The interface that allows external functions to iterate its own internal data is Iterator interface
, and the corresponding iterated self is Iterator object
.
PHP provides a unified iterator interface:
Iterator extends Traversable { // 返回当前的元素 abstract public mixed current(void) // 返回当前元素的键 abstract public scalar key(void) // 向下移动到下一个元素 abstract public void next(void) // 返回到迭代器的第一个元素 abstract public void rewind(void) // 检查当前位置是否有效 abstract public boolean valid(void)}
By implementing the Iterator interface
, we can decide how to traverse the object by ourselves.
Foreach works because these collection classes all implement the Iterable interface, which defines the generation method of Iterator, and foreach moves in the sequence through the Iterable interface.
Compared with iterators, generators provide an easier way to implement simple object iteration
, with less performance overhead and complexity. Greatly reduced.
A generator function looks like an ordinary function. The difference is that an ordinary function returns a value, while a generator can yield
generate many values, and each yield just pauses. The current execution state, when the generator function is called next time, PHP will continue execution from the last paused state.
When we use the generator, we can specify a key name corresponding to the generated value like an associative array. Generating a key-value pair as follows is similar to defining an associative array.
function xrange($start, $limit, $step = 1) { for ($i = $start, $j = 0; $i <= $limit; $i += $step, $j++) { // 给予键值 yield $j => $i; } }$xrange = xrange(1, 10, 2);foreach ($xrange as $key => $value) { echo $key . ' => ' . $value . "\n";}
First clarify a concept: The yield keyword of the generator is not a return value. Its professional term is called output value, which just generates a value. In fact, the generator function returns a Generator
object, which cannot be instantiated through new and implements the Iterator
interface.
So what is the loop in the code foreach? When PHP uses a generator, it will return an object of class Generator. foreach The object can be iterated. For each iteration, PHP will calculate the value that needs to be iterated next through the Generator instance. In this way foreach will know the value that needs to be iterated next.
Moreover, during operation, for will stop immediately after the loop is executed. Wait for foreach to ask for for the next value again during the next loop, and then the loop will be executed again, and then immediately Stop again. It will not be executed until the conditions are not met.
Advantages of generators
Generators will have a great impact on the performance of PHP applications
PHP code saves a lot of memory when running
It is more suitable for calculating large amounts of data
PHP development often requires reading large files, such as csv files, text files, or some log files. If these files are large, such as 5G. At this time, it is not practical to directly read all the contents into the memory at once. Use the generator to read the file. The first line is read for the first time, the second line is read for the second time, and so on. There is only one line of text loaded into the memory each time, which is greatly Reduced memory usage.
<?php header("content-type:text/html;charset=utf-8"); function readTxt() { # code... $handle = fopen("./test.txt", 'rb'); while (feof($handle)===false) { # code... yield fgets($handle); } fclose($handle); } foreach (readTxt() as $key => $value) { # code... echo $value.'<br />'; }
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
PHP uses Azure Storage Blob to upload files
Introduction to curl requesting other interfaces in the php interface
The above is the detailed content of Introduction to PHP iterator generators. For more information, please follow other related articles on the PHP Chinese website!