Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexsasharegan/c1c1c2de326bf6385ea70e35c6d43dc5 to your computer and use it in GitHub Desktop.
Save alexsasharegan/c1c1c2de326bf6385ea70e35c6d43dc5 to your computer and use it in GitHub Desktop.
Use reflection to get an array of both visible & hidden object properties. Handles nested objects recursively.
<?php
function extractAllObjectPropsToArray( $object )
{
$properties = [];
$reflection = new ReflectionClass( $object );
foreach ( $reflection->getProperties() as $property )
{
$property->setAccessible( TRUE );
$propName = $property->getName();
$propValue = property_exists( $object, $propName )
? $property->getValue( $object )
: NULL;
switch ( TRUE )
{
case is_array( $propValue ):
$properties[ $propName ] = [];
foreach ( $propValue as $value )
{
$properties[ $propName ][] = is_object( $value )
? extractAllObjectPropsToArray( $value )
: $properties[ $propName ][] = $value;
}
break;
case is_object( $propValue ):
$properties[ $propName ] = extractAllObjectPropsToArray( $propValue );
break;
default:
$properties[ $propName ] = $propValue;
break;
}
}
return $properties;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment