PHP如何在Object中找到正确的属性

时间:2013-07-15 16:15:45

标签: php object conditional

class a {
    public $a = "3";
    public $b = "0";
    public $b = "3";
    public $c = "0";
    public $d = "0";
    public $e = "0";
    public $g = "0";
}

如何找出哪些属性大于零?

2 个答案:

答案 0 :(得分:0)

你可以在对象本身之外使用get_class_vars函数:

$a = new a();

$class_vars = get_class_vars(get_class($a));

foreach ($class_vars as $name => $value) {
    if ($value > 0) {
         echo "$name : $value\n";
    }
}

答案 1 :(得分:0)

将此方法放入您的类中,它将返回数组中的所有变量:

public function test() {
    $vars = get_object_vars($this);
    $r = array();
    foreach($vars as $k => $v) {
        if($v > 0){ $r[$k] = $v; }
    }
    return $r;
}