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:

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:

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