Looping through all the properties of object php

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

Before you run the $obj through a foreach loop you have to convert it to an array (see: cast to array) if you're looking for properties regardless of visibility.

Example with HTML output (PHP 8.1):

foreach ((array)$obj as $key => $val) {
    printf(
        "%s: %s<br>\n", 
        htmlspecialchars("$key"), 
        htmlspecialchars("$val"),
    );
}

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

Tags:

Php