How can i iterate over the (public or private) properties of a php class?
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();
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!
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).
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 }
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