Just like we do with __ToString, is there a way to define a method for casting?
$obj = (MyClass) $another_class_obj;
You can create two reflection object then copy values to other example can be found at https://github.com/tarikflz/phpCast
public static function cast($sourceObject)
{
$destinationObject = new self();
try {
$reflectedSource = new ReflectionObject($sourceObject);
$reflectedDestination = new ReflectionObject($destinationObject);
$sourceProperties = $reflectedSource->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($reflectedDestination->hasProperty($name)) {
$propDest = $reflectedDestination->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destinationObject, $value);
} else {
$destinationObject->$name = $value;
}
}
} catch (ReflectionException $exception) {
return $sourceObject;
}
return $destinationObject;
}