PHP display nested Object with array of other Object as 1 nested array

There are a few issues, that make this difficult.

  • Property visibility, (private, protected) can cause issues when trying to read them outside of the class, proper. This is expected behavior as that's the point to not use public.

  • Classes are different. They are well defined and we know them ahead of time, but they are too diverse to account of all property names, at least not with a lot of wasted effort. Not to mention defining them "hard coding" would bite you later as it would make it difficult to maintain. For example if one of the packages does an update and you have coded the property names in you may have issues if they change them. On top of this given that these properties are not part of the classes Public "API" but instead part of the internals, it would not be unreasonable for them to change.

  • Properties can contain a mix of data types, including other classes or objects. This can make it challenging to handle.

  • Classes are part of other packages/frameworks and editing them is not practical, this restricts us to working outside of these classes.

So given these difficulties I would recommend using reflection to access the protected properties. Reflection allows you to inspect the definition of classes (and other stuff).

function jsonSerialize($obj){
    return json_encode(toArray($obj));
}

function toArray($obj){
    $R = new ReflectionObject($obj);
    $proerties = $R->getProperties();
    $data = [];

    foreach($proerties as $k => $v){
        $v->setAccessible(true);
        $property = $v->getName();
        $value = $v->getValue($obj);

        if(!is_object($value)){
            $data[$property] = $value;    
        }else if( is_a($obj,'\\DateTime')){
            //if its a descendant of Datetime, get a formatted date.
            // you can add other special case classes in this way
            $data[$property] = $value->format('Y-m-d H:i:s');
        }else{
           $data[$property] = toArray($value); //call recursively
        }
    }
    return $data;
}

So assume we have these classes

class foo{
    private $bar; //private nested object

    public function __construct(){
        $this->bar = new bar();

    }

}

class bar{
    private $something = 'hello';
}

$obj = new foo;

echo jsonSerialize($obj);

See it in a sandbox here

Outputs:

{"bar":{"something":"hello"}}

Also of note is we have a special consideration for the DateTime class. Instead of getting all the properties of this we just want the date (probably) formatted in some standard way. So by using is_a() (I'm old school) we can tell if the Object $value has a given class as an ancestor of it. Then we just do our formatting.

There are probably a few special cases like this, so I wanted to mention how to handle them.