3v4l.org

run code in 300+ PHP versions simultaneously
<?php class myData implements IteratorAggregate { public $property1 = "Public property one"; public $property2 = "Public property two"; public $property3 = "Public property three"; public $property4; public function __construct() { $this->property4 = "last property"; } public function getIterator() : ArrayIterator { return new ArrayIterator($this); } } class myIterator implements Iterator { private $position = 0; private $array = array('one', 'two', 'three'); function rewind(): void { $this->position = 0; } function current(): mixed { return $this->array[$this->position]; } function key(): mixed { return $this->position; } function next(): void { ++$this->position; } function valid(): bool { return isset($this->array[$this->position]); } } $renderFunction = function($iterator) { foreach($iterator as $key => $value) { echo "$key: $value\n"; foreach($iterator as $key => $value) { echo " $key: $value\n"; } } }; echo "-----IteratorAggregate-----\n"; $renderFunction(new myData); echo "\n-----Iterator-----\n"; $renderFunction(new myIterator);
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
-----IteratorAggregate----- property1: Public property one property1: Public property one property2: Public property two property3: Public property three property4: last property property2: Public property two property1: Public property one property2: Public property two property3: Public property three property4: last property property3: Public property three property1: Public property one property2: Public property two property3: Public property three property4: last property property4: last property property1: Public property one property2: Public property two property3: Public property three property4: last property -----Iterator----- 0: one 0: one 1: two 2: three

preferences:
81.67 ms | 408 KiB | 5 Q