Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through all the properties of object php

Tags:

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)   
like image 713
Daric Avatar asked Feb 12 '11 06:02

Daric


People also ask

Which loop is used to loop through an object properties?

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).

How do I iterate over an object in PHP?

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();

How do you access the properties of an object in PHP?

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 .


2 Answers

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"; } 
like image 149
David Harkness Avatar answered Oct 18 '22 14:10

David Harkness


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));  
like image 36
Dimi Avatar answered Oct 18 '22 12:10

Dimi