Last active
September 7, 2016 12:21
-
-
Save Tiriel/c43f54fcb77b93eb1194cc0c06db419e to your computer and use it in GitHub Desktop.
Class casting function from StackOverflow
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 | |
/** | |
* 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