Home > Article > Backend Development > The role and examples of yield keyword in PHP
The yield keyword in PHP is a keyword introduced in PHP 5.5, which can be used to create a generator inside a function. Generators can be used to iterate over a large data set without loading the entire data set into memory at once.
The yield keyword is to turn the current function into a generator function. Inside the generator function, we can use the yield statement to return a value to the caller, and the execution status of the generator function will be saved. The next time the generator function is called, execution will continue from the last yield statement.
Next, let us illustrate the role of the yield keyword through some sample code.
First, let’s create a simple generator function to generate an integer sequence from 1 to 10:
function generateNumbers() { for ($i = 1; $i <= 10; $i++) { yield $i; } } foreach (generateNumbers() as $number) { echo $number . " "; }
The output of the above code is: 1 2 3 4 5 6 7 8 9 10
In this example, the generateNumbers() function returns a generator object. We traverse this generator object through a foreach loop, and each traversal will return a value from the yield statement. The advantage of this is that the entire sequence does not need to be stored in memory at once, but the corresponding values are generated and returned on demand.
Next, let’s look at a more practical example. Suppose we need to read a very large file, but loading the entire file into memory at once will cause memory overflow problems. At this time, we can use the generator function to read the file line by line:
function readFileByLine($file) { $handle = fopen($file, "r"); if ($handle) { while (($line = fgets($handle)) !== false) { yield $line; } fclose($handle); } } foreach (readFileByLine("big_file.txt") as $line) { echo $line; }
The above code will read the contents of the file line by line and return the content of each line to the caller. This way we can read one line at a time without loading the entire file into memory at once.
In addition to using the yield keyword inside a function to create a generator function, the yield keyword can also be used with iterable objects to implement more complex functions. Through the yield keyword, we can define our own iteration rules and provide customized traversal methods.
To sum up, the function of yield keyword in PHP is to create a generator function to generate and return values on demand. Generator functions can be used in scenarios such as traversing large data sets or reading large files line by line to reduce memory overhead. Using the yield keyword can improve code execution efficiency and reduce memory consumption.
The above is the detailed content of The role and examples of yield keyword in PHP. For more information, please follow other related articles on the PHP Chinese website!