Iterating through an object

Did you knew that you could iterate through an objects variables? Well I did, but I already forgot that it was possible.

Take a look at the following class:

<?php

class Car {
    public $tires = 4;
    public $doors = 5;
    public $color = "black";
    public $manufacturer = "Ferrari";
    protected $secret = "This is something you may not read";
}

If you use the class mentioned above in some other file, you can iterate through its variables like:

<?php

require_once 'car.class.php';

$car = new Car();
foreach($car as $car_detail => $value) {
    print $car_detail." => ".$value." <br>";
}

This results in the output of:

<?php
tires => 4
doors => 5
color => black
manufacturer => Ferrari

If you paid really good attention to the class, you might notice that the secret variable is NOT included in our output. This is completely normal like, you cannot access the variable directly when it’s a protected variable.

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *