Home  >  Article  >  Backend Development  >  Comparison of PHP generators and iterator objects

Comparison of PHP generators and iterator objects

王林
王林forward
2023-09-16 17:41:02952browse

Comparison of PHP generators and iterator objects

Introduction

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

  • Iterator::current - Returns the current element
  • Iterator: :key - Returns the current element Key of the element
  • Iterator::next — Move forward to the next element
  • Iterator: :rewind — Rewind the iterator to the first element
  • Iterator::valid — Checks if the current position is valid

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.

Generators as Interactors

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

Example

<?php
function filegenerator($name) {
   $fileHandle = fopen($name, &#39;r&#39;);
   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();
?>

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete