3v4l.org

run code in 300+ PHP versions simultaneously
<?php function cast($source, $class) { try { $sourceReflection = new ReflectionClass($source); $targetReflection = new ReflectionClass($class); $targetProperties = $targetReflection->getProperties(); $target = $targetReflection->newInstanceWithoutConstructor(); foreach ($targetProperties as $targetProperty) { $name = $targetProperty->getName(); if ($sourceReflection->hasProperty($name)) { $sourceProperty = $sourceReflection->getProperty($name); $sourceProperty->setAccessible(true); $targetProperty->setAccessible(true); $targetProperty->setValue($target, $sourceProperty->getValue($source)); } } return $target; } catch (ReflectionException $reflectionException) { return null; } } class Foo { private $a = __CLASS__; private $b = __CLASS__; private $c = __CLASS__; } class Bar { private $b = __CLASS__; private $c = __CLASS__; private $d = __CLASS__; } $foo = new Foo(); $bar = cast($foo, 'Bar'); var_dump($bar);

preferences:
34.33 ms | 402 KiB | 5 Q