Skip to content

Instantly share code, notes, and snippets.

@Neferetheka
Created July 23, 2014 13:23
Show Gist options
  • Save Neferetheka/20714e7b1ce81684c4d9 to your computer and use it in GitHub Desktop.
Save Neferetheka/20714e7b1ce81684c4d9 to your computer and use it in GitHub Desktop.
PHP method to create an array from an object using Reflection
/**
* 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