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";
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?