In PHP, how do I iterate over objects with examples?

In PHP, you can iterate over objects using a variety of methods. The two most common approaches are using a foreach loop and implementing the Iterator interface. Below are examples illustrating both methods.

Example of iterating over an object using a foreach loop:

<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $person = new Person("John", 30); foreach ($person as $property => $value) { echo "$property: $value\n"; } ?>

Example of iterating over an object using the Iterator interface:

<?php class Person implements Iterator { private $people = []; private $position = 0; public function __construct() { $this->people = [ "John" => 30, "Jane" => 25, ]; } public function current() { return $this->people[$this->key()]; } public function key() { return array_keys($this->people)[$this->position]; } public function next() { ++$this->position; } public function rewind() { $this->position = 0; } public function valid() { return isset($this->people[$this->key()]); } } $person = new Person(); foreach ($person as $name => $age) { echo "$name: $age\n"; } ?>

PHP Iterate over objects foreach Iterator interface