
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP Generators vs Iterator objects
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
- Related Articles
- PHP Generators.
- Iterator vs ListIterator in Java?
- Iterator vs forEach in Java
- Iterator vs Collection in Java
- PHP Objects.
- PHP Comparing Objects
- PHP readfile vs. file_get_contents
- PHP Objects and references
- ‘AND’ vs ‘&&’ operators in PHP
- The Byte Objects vs String in Python
- Storing objects in PHP session
- Creating anonymous objects in PHP
- Generators in Python?
- Types DC Generators
- Types of Generators

Advertisements