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)
Object. Before ES6, the only way to loop through an object was through using the for...in loop. The Object. keys() method was introduced in ES6 to make it easier to loop over objects. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys).
PHP provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration. echo "\n"; $class->iterateVisible();
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
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"; }
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With