Created
March 24, 2017 16:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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