Answer: Generators and iterators are special functions and objects that can generate values one by one without storing the entire data set. Generator: Generates a series of values, one value for each call; Iterator: Provides a method to access collection elements, and generates an element when traversing; Practical combat: Used for paging, generating data sets page by page, without storing the entire data set in in memory.
PHP Advanced Features: The Magical Use of Generators and Iterators
Generator
A generator is a special function used to generate a series of values. Unlike regular functions, generators can produce a value on each call without storing the entire array of values in memory.
function numbersGenerator() { for ($i = 1; $i <= 10; $i++) { yield $i; } } foreach (numbersGenerator() as $number) { echo $number . "\n"; }
Iterator
An iterator is an object that provides a way to access elements in a collection. Like generators, iterators can generate an element while iterating through a collection without storing the entire collection in memory.
class NumberIterator implements Iterator { private $start; private $end; private $current; public function __construct($start, $end) { $this->start = $start; $this->end = $end; $this->current = $start; } public function rewind() { $this->current = $this->start; } public function current() { return $this->current; } public function key() { return $this->current; } public function next() { $this->current++; } public function valid() { return $this->current <= $this->end; } } $iterator = new NumberIterator(1, 10); foreach ($iterator as $number) { echo $number . "\n"; }
Practical case: Paginator
Generators and iterators are very suitable for paging scenarios. By using generators or iterators we can generate the dataset page by page without storing the entire dataset in memory.
function paginate($query, $pageSize) { $page = 1; while (true) { $offset = ($page - 1) * $pageSize; $results = $query->offset($offset)->limit($pageSize)->execute(); if (count($results) === 0) { break; } yield $results; $page++; } } foreach (paginate($query, 10) as $page) { echo "Page $page\n"; foreach ($page as $result) { // Process the result } }
The above is the detailed content of PHP advanced features: the wonderful uses of generators and iterators. For more information, please follow other related articles on the PHP Chinese website!