Object Properties Iteration

Since objects are quite similar to arrays, it is possible iterate through it's properties with a foreach loop.

 

  • properties must be accessible
  • private and protected are not accessible in the general scope

 

This example instantiates an object from a simple class with a number of properties that the foreach loop then iterates through. Note the private property on line 6 is not accessible outside the class:

<?php
	class Bike {
		public $make = "Yamaha";
		public $model = "YZFR1";
		public $cost = 12999;
		private $topSpeed = 165;
		public $mpg = 67;
		public $colour = "Blue";
		public $country = "Japan";
		public $bhp = 146;
		}
	$racer = new Bike;
	foreach($racer as $key => $value) {
		echo "$key = $value<br>";
	}
?>

Save & refresh browser:

make = Yamaha
model = YZFR1
cost = 12999
mpg = 67
colour = Blue
country = Japan

bhp = 146

 

 

To access private/protected properties, the foreach loop is moved into the class as a method:

<?php
	class Bike {
		public $make = "Yamaha";
		public $model = "YZFR1";
		public $cost = 12999;
		private $topSpeed = 165;
		public $mpg = 67;
		public $colour = "Blue";
		public $country = "Japan";
		protected $bhp = 146;

		public function display(){
			foreach($this as $key => $value){
				echo "$key = $value<br>";
			}
		}
	}
	$racer = new Bike;
	$racer->display();
?>

Save & refresh browser:

make = Yamaha
model = YZFR1
cost = 12999
topSpeed = 165
mpg = 67
colour = Blue
country = Japan
bhp = 146

 

Since the object itself is iterating through it's own properties, private and protected properties can now be accessed.

Leave a Reply