Created
July 23, 2014 13:23
-
-
Save Neferetheka/20714e7b1ce81684c4d9 to your computer and use it in GitHub Desktop.
PHP method to create an array from an object using Reflection
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
/** | |
* Awesome method to create an array from an object using Reflection. Useful for JSON serialization | |
* @return array : array of object properties. | |
*/ | |
public function asArray() | |
{ | |
$reflectionClass = new ReflectionClass(get_class($this)); | |
$array = array(); | |
foreach ($reflectionClass->getProperties() as $property) { | |
$property->setAccessible(true); | |
$array[$property->getName()] = $property->getValue($this); | |
$property->setAccessible(false); | |
} | |
return $array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment