<!DOCTYPE html>
<html>
<body>
<?php
// Создать итератор
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public function __construct($items) {
// array_values() следит за тем, чтобы ключи были числами
$this->items = array_values($items);
}
public function current() {
return $this->items[$this->pointer];
}
public function key() {
return $this->pointer;
}
public function next() {
$this->pointer++;
}
public function rewind() {
$this->pointer = 0;
}
public function valid() {
// count() указывает, сколько элементов в списке
return $this->pointer < count($this->items);
}
}
// Функция, использующая итерируемые объекты
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
// Используйте итератор как повторяемый объект
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>
</body>
</html>