PHP Iterating Object Properties
Description
We can treat an object as an array with the foreach loop. foreach will iterate over each of the properties that are accessible.
That is, private and protected properties will not be accessible in the general scope.
Example
Take a look at this script:
<?PHP/*w ww . j a v a2 s.c o m*/
class Person {
public $FirstName = "James";
public $MiddleName = "Tuple";
public $LastName = "List";
private $Password = "pass";
public $Age = 29;
public $HomeTown = "LA";
}
$bill = new Person();
foreach($bill as $var => $value) {
echo "$var is $value\n";
}
?>
The code above generates the following result.
Note that the $Password
property is nowhere in sight, because it is marked Private.
If the foreach
loop is called inside a method, we should be able to see the
property:
<?PHP// w w w.jav a 2 s . co m
class Person {
public $FirstName = "James";
public $MiddleName = "Tuple";
public $LastName = "List";
private $Password = "pass";
public $Age = 29;
public $HomeTown = "LA";
public function outputVars() {
foreach($this as $var => $value) {
echo "$var is $value\n";
}
}
}
$bill = new Person();
$bill->outputVars();
?>
The code above generates the following result.