Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over properties of a php class

Tags:

How can i iterate over the (public or private) properties of a php class?

like image 648
Cameron A. Ellis Avatar asked May 14 '09 02:05

Cameron A. Ellis


People also ask

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?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

What line of code is used to iterate through all the properties of an object?

Description. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).


1 Answers

tl;dr

// iterate public vars of class instance $class foreach (get_object_vars($class) as $prop_name => $prop_value) {    echo "$prop_name: $prop_value\n"; } 

Further Example:

http://php.net/get_object_vars

Gets the accessible non-static properties of the given object according to scope.

class foo {     private $a;     public $b = 1;     public $c;     private $d;     static $e; // statics never returned      public function test() {         var_dump(get_object_vars($this)); // private's will show     } }  $test = new foo;  var_dump(get_object_vars($test)); // private's won't show  $test->test(); 

Output:

array(2) {   ["b"]=> int(1)   ["c"]=> NULL }  array(4) {   ["a"]=> NULL   ["b"]=> int(1)   ["c"]=> NULL   ["d"]=> NULL } 
like image 101
Louis Avatar answered Sep 19 '22 17:09

Louis