Looping through all the properties of object php

How can I loop through all the properties of object?. Right now I have to write a new code line to print each property of object

echo $obj->name;
echo $obj->age;

Can I loop through all the properties of an object using foreach loop or any loop?

Something like this

foreach ($obj as $property => $value)  

Solution 1:

If this is just for debugging output, you can use the following to see all the types and values as well.

var_dump($obj);

If you want more control over the output you can use this:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}

Solution 2:

For testing purposes I use the following:

//return assoc array when called from outside the class it will only contain public properties and values 
var_dump(get_object_vars($obj)); 

Solution 3:

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

Solution 4:

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)