Comparison of PHP generators and iterator objects

王林
Release: 2023-09-16 17:42:02
forward
990 people have browsed it

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();
?>
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template