iterate over properties of a php class
12,034
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
}
Author by
Cameron A. Ellis
Updated on June 03, 2022Comments
-
Cameron A. Ellis about 2 years
How can i iterate over the (public or private) properties of a php class?
-
lsl about 15 yearsyes, however only the public vars will be displayed, private ones are returned only when the caller of get_object_vars is inside the class.
-
Daniel Sorichetti about 15 yearsYep, as Lou said, <a href="nz.php.net/get_object_vars">get_object_vars</a> is the function you need.