PHP Iterating Object Properties

In this chapter you will learn:

  1. How to Iterating Object Properties
  2. Example - 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/*  j ava2 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//j ava 2  s . c  o 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.

Next chapter...

What you will learn in the next chapter:

  1. What is Class Inheritance
  2. Syntax to create Inheritance
  3. Example - create Inheritance
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods