How to Cast Objects in PHP
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) { $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;}
EXAMPLE:
class A { private $_x; }class B { public $_x; }$a = new A();$b = new B();$x = cast('A',$b);$x = cast('B',$a);
There is no built-in method for type casting of user defined objects in PHP. That said, here are several possible solutions:
1) Use a function like the one below to deserialize the object, alter the string so that the properties you need are included in the new object once it's deserialized.
function cast($obj, $to_class) { if(class_exists($to_class)) { $obj_in = serialize($obj); $obj_out = 'O:' . strlen($to_class) . ':"' . $to_class . '":' . substr($obj_in, $obj_in[2] + 7); return unserialize($obj_out); } else return false;}
2) Alternatively, you could copy the object's properties using reflection / manually iterating through them all or using get_object_vars().
This article should enlighten you on the "dark corners of PHP" and implementing typecasting on the user level.
Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform
one class to another with preassumption of the developer knows and understand the similarity of 2 classes.
There's no existing solution for transforming between objects. What you can try out are:
- get_object_vars() : convert object to array
- Cast to Object: convert array to object