How to loop through an array of objects
Written: 2010-02-05 06:55:54<?php
class Person{
//Fields
private $name;
private $age;
private $id;
//Properties
public function getName() { return $this->name; }
public function getAge() { return $this->age; }
public function getId() { return $this->id; }
public function setName($name) { $this->name = $name; }
public function setAge($age) { $this->age = $age; }
public function setId($id) { $this->id = $id; }
//Construct
public function __construct($name, $age){
$this->setName($name);
$this->setAge($age);
}
}
//=================Run program========================
//Create some people
$p1 = new Person("John", 45);
$p2 = new Person("Lisa", 34);
$p3 = new Person("Jake", 12);
//Create an array of Person objects
$people = array($p1, $p2, $p3);
//Output the objects in the array
for($i = 0; $i < sizeof($people); $i++){
if(is_object($people[$i])){
$people[$i]->setId($i + 1);
}
else {
echo "Error at loop index ".$i."<br />";
echo "<pre>";
echo var_dump($people[$i]);
echo "</pre>";
}
}
echo "<pre>";
print_r($people);
echo "</pre>";
?>
Array
(
[0] => Person Object
(
[name:private] => John
[age:private] => 45
[id:private] => 1
)
[1] => Person Object
(
[name:private] => Lisa
[age:private] => 34
[id:private] => 2
)
[2] => Person Object
(
[name:private] => Jake
[age:private] => 12
[id:private] => 3
)
)