迭代 php 类的属性
如何迭代php类的(公共或私有)属性?
tl;博士
// iterate public vars of class instance $class
foreach (get_object_vars($class) as $prop_name => $prop_value) {
echo "$prop_name: $prop_value\n";
}
进一步的示例:
http://php.net/get_object_vars
根据作用域获取给定对象的可访问非静态属性。
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();
输出:
array(2) {
["b"]=> int(1)
["c"]=> NULL
}
array(4) {
["a"]=> NULL
["b"]=> int(1)
["c"]=> NULL
["d"]=> NULL
}