What is the main purpose of using the Iterator Pattern in PHP?
The main purpose of using the Iterator Pattern in PHP is to provide a way to access the elements of a collection without exposing its underlying representation. This pattern allows you to iterate over a collection of objects without needing to know the specific structure of the collection. It provides a standardized way to traverse through a collection, making the code more flexible and reusable.
// Define an interface for iterators
interface IteratorInterface {
public function hasNext();
public function next();
}
// Implement an iterator for a specific collection
class CollectionIterator implements IteratorInterface {
private $collection;
private $index = 0;
public function __construct($collection) {
$this->collection = $collection;
}
public function hasNext() {
return $this->index < count($this->collection);
}
public function next() {
$element = $this->collection[$this->index];
$this->index++;
return $element;
}
}
// Usage example
$collection = [1, 2, 3, 4, 5];
$iterator = new CollectionIterator($collection);
while ($iterator->hasNext()) {
echo $iterator->next() . "\n";
}