views:

435

answers:

2

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

+6  A: 

http://nz.php.net/get_object_vars

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function test() {
        var_dump(get_object_vars($this));
    }
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

Make sense?

jim
So could i do a: foreach(get_object_vars($this) as $prop=>$val) ?
cellis
yes, however only the public vars will be displayed, private ones are returned only when the caller of get_object_vars is inside the class.
jim
A: 

Yep, as Lou said, get_object_vars is the function you need.

Daniel S