遍历php类的属性 [英] iterate over properties of a php class

查看:50
本文介绍了遍历php类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何遍历php类的(公共或私有)属性?

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

推荐答案

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";
}

进一步的示例:

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();

输出:

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

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

这篇关于遍历php类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆