Junior — Middle
Have you used the iterator pattern or similar mechanisms for traversing collections in your projects?
sobes.tech AI
Answer from AI
Yes, in PHP I often used the iterator pattern to traverse collections, especially when I needed to hide the internal data structure or implement a custom traversal method.
PHP provides the Iterator interface, which can be implemented in a class to support traversal via foreach. This is convenient when the collection is complex or when you need to control the order and conditions of traversal.
Here's an example of a simple iterator:
class MyCollection implements Iterator {
private $items = [];
private $position = 0;
public function __construct($items) {
$this->items = $items;
$this->position = 0;
}
public function current() {
return $this->items[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function rewind() {
$this->position = 0;
}
public function valid() {
return isset($this->items[$this->position]);
}
}
$collection = new MyCollection([1, 2, 3]);
foreach ($collection as $item) {
echo $item . "\n";
}
This approach improves encapsulation and flexibility when working with data.