Skip to content

Instantly share code, notes, and snippets.

@Tiriel
Last active September 7, 2016 12:21
Show Gist options
  • Save Tiriel/c43f54fcb77b93eb1194cc0c06db419e to your computer and use it in GitHub Desktop.
Save Tiriel/c43f54fcb77b93eb1194cc0c06db419e to your computer and use it in GitHub Desktop.
Class casting function from StackOverflow
<?php
/**
* Class casting
*
* @param string|object $destination
* @param object $sourceObject
* @return object
*/
function cast($destination, $sourceObject)
{
if (is_string($destination)) {
$destination = new $destination();
}
$sourceReflection = new ReflectionObject($sourceObject);
$destinationReflection = new ReflectionObject($destination);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name)) {
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
} else {
$destination->$name = $value;
}
}
return $destination;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment