Skip to content
Advertisement

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

I have big Object with protected properties and a property can be an array of other Objects. My goal is to print this entire Object as a single nested array. So I need to convert the object to an array.

I’ve tried doing:

$result = (array) $object;

But this converts only the highest lever object to an array and it messes up my protected properties names with weird question mark signs.

I’ve also tried something like this but this simply returns an empty array:

$result= json_decode(json_encode($object), true);

Here is what my object looks like:

JavaScript

EDIT

I have a method in my class where I “find” the result that looks like this:

JavaScript

Advertisement

Answer

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

JavaScript

So assume we have these classes

JavaScript

See it in a sandbox here

Outputs:

JavaScript

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement