The Street Way

Iterating Through Object Properties


We can treat an object as an array with the 'foreach' loop, and it will iterate over each of the properties inside that object that are accessible. That is, private and protected properties will not be accessible in the general scope. Take a look at this script:

class Person {
            public $FirstName = "ABC";
            public $MiddleName = "PQR";
            public $LastName = "XYZ";
            private $Password = "ABC_12";
            public $Age = 27;
            public $HomeTown = "NewYork";
            public $FavouriteColor = "Pink";
    }

    $d = new Person( );

    foreach($d as $var => $value) {
            echo "$var is $value\n";
    }


That will output this:

    FirstName is ABC
    MiddleName is PQR
    LastName is XYZ
    Age is 27   
    HomeTown is NewYork
    FavouriteColor is Pink


Note that the '$Password' property is nowhere in sight, because it is marked Private and we're trying to access it from the global scope. If we re-fiddle the script a little so that the 'foreach' loop is called inside a method, we should be able to see the property:

class Person {
            public $FirstName = "ABC";
            public $MiddleName = "PQR";
            public $LastName = "XYZ";
            private $Password = "ABC_12";
            public $Age = 27;
            public $HomeTown = "NewYork";
            public $FavouriteColor = "Pink";

    public function outputVars( ) {

                     foreach($this as $var => $value) {
                            print "$var is $value\n";
                    }
            }
    }

    $d = new Person( );
    $d->outputVars( );


Now the output is this:

    FirstName is ABC
    MiddleName is PQR
    LastName is XYZ
    Password is ABC_12
    Age is 27
    HomeTown is NewYork
    FavouriteColor is Pink


Now that it's the object itself looping through its properties, we can see private properties just fine. Looping through objects this way is a great way to hand write serialization methods just remember to put the code inside a method; otherwise, private and protected data will get ignored.

0 comments:

Post a Comment