[英]iterate over properties of a php class
如何遍歷 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.