How to Cast Objects in PHP


Ive some classes that share some attributes, and i would like to do something like:

$dog = (Dog) $cat;

is it possible or is there any generic work around?

Its not a superclass, or a interface or related in any way. They are just 2 different classes i would like php map the attributes from a cat class to a dog and give me the new object. –

i guess i have to specify a little bit more cause seem like a senseless thing to do.

i've classes that inherits from different parent classes cause i've made an inheritance tree based on the saving method, maybe my bad from the beginning, but the problem is that i have a lot of classes that are practically equal but interacts one with mysql and the other one with xml files. so i have:

class MySql_SomeEntity extends SomeMysqlInteract{}


Xml_SomeEntity extends SomeXmlInteract{}

its a little bit deeper tree but the problem its that. i cant make them inherits from the same class cause multiple inheritance is not allowed, and i cant separate current interaction with superclases cause would be a big trouble.

Basically the attributes in each one are practical the same.

since i have a lot of this matching classes i would like to do some generic casting or something like it that can converts (pass the values to each attribute) and but im trying to search the simplest way to everyone of this classes.

4/4/2019 8:36:14 AM

You can use above function for casting not similar class objects (PHP >= 5.3)

 * 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) {
        $name = $sourceProperty->getName();
        $value = $sourceProperty->getValue($sourceObject);
        if ($destinationReflection->hasProperty($name)) {
            $propDest = $destinationReflection->getProperty($name);
        } else {
            $destination->$name = $value;
    return $destination;


class A 
  private $_x;   

class B 
  public $_x;   

$a = new A();
$b = new B();

$x = cast('A',$b);
$x = cast('B',$a);
3/21/2012 8:05:43 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow