Looping through all the properties of object php

后端 未结 4 814
日久生厌
日久生厌 2020-11-29 05:29

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 $ob         


        
相关标签:
4条回答
  • 2020-11-29 06:12

    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";
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    Here is another way to express the object property.

    foreach ($obj as $key=>$value) {
        echo "$key => $obj[$key]\n";
    }
    
    0 讨论(0)
  • 2020-11-29 06:19

    Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

    0 讨论(0)
  • 2020-11-29 06:22

    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)); 
    
    0 讨论(0)
提交回复
热议问题