gpt4 book ai didi

php - 遍历 php 类的属性

转载 作者:IT王子 更新时间:2023-10-29 00:07:25 24 4
gpt4 key购买 nike

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

最佳答案

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 - 遍历 php 类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/861254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com