PHP Generators vs Iterator objects

PHPServer Side ProgrammingProgramming

Introduction

When a generator function is called, internally, a new object of Generator class is returned. It implements the Iterator interface. The iterator interface defines following abstract methods

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

Generator acts as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.

Generator as interator

In following example, generator functions yields lines in a file in a generator object which can be traversed using oreach loop. Iterator methods such as current() and next() can also be invoked. However, since generator is forward-only iterator, calling rewind() method throws exception

Example

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

Output

After traversal of file lines, fatal error as shown below 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
raja
Published on 18-Sep-2020 09:12:48
Advertisements