When a generator function is called, a new Generator class object is returned internally. It implements the Iterator interface. The iterator interface defines the following abstract methods
The generator acts as a forward-only iterator Object and provides callable methods to manipulate the generator's state, including sending values to and returning values from the generator.
In the following example, the generator function generates lines in the file of the generator object, which can be iterated over using an oreach loop. Iterator methods such as current() and next() can also be called. However, since the generator is a forward-only iterator, calling the rewind() method throws an exception
<?php function filegenerator($name) { $fileHandle = fopen($name, 'r'); while ($line = fgets($fileHandle)) { yield $line; } fclose($fileHandle); } $name="test.txt"; $file=filegenerator($name); foreach ($file as $line) echo $line; $file->rewind(); echo $file->current(); $file->next(); echo $file->current(); ?>
Traversal After the file line, the following fatal error is displayed
PHP User Defined Functions PHP Function Arguments PHP Variable Functions PHP Internal (Built-in) Functions PHP Anonymous functions PHP Arrow Functions PHP Fatal error: Uncaught Exception: Cannot rewind a generator that was already run
The above is the detailed content of Comparison of PHP generators and iterator objects. For more information, please follow other related articles on the PHP Chinese website!