循环遍历对象 php 的所有属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4976624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:24:47  来源:igfitidea点击:

Looping through all the properties of object php

php

提问by Daric

How can I loop through all the properties of object?. Right now I have to write a new code line to print each property of object

如何遍历对象的所有属性?现在我必须编写一个新的代码行来打印对象的每个属性

echo $obj->name;
echo $obj->age;

Can I loop through all the properties of an object using foreach loop or any loop?

我可以使用 foreach 循环或任何循环遍历对象的所有属性吗?

Something like this

像这样的东西

foreach ($obj as $property => $value)  

回答by David Harkness

If this is just for debugging output, you can use the following to see all the types and values as well.

如果这只是为了调试输出,您也可以使用以下命令查看所有类型和值。

var_dump($obj);

If you want more control over the output you can use this:

如果你想更多地控制输出,你可以使用这个:

foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}

回答by Dimi

For testing purposes I use the following:

出于测试目的,我使用以下内容:

//return assoc array when called from outside the class it will only contain public properties and values 
var_dump(get_object_vars($obj)); 

回答by Budove

Here is another way to express the object property.

这是表达对象属性的另一种方式。

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}