Convert/cast an stdClass object to another class

04/21/2020 11:30:01

I'm using a third party storage system that only returns me stdClass objects no matter what I feed in for some obscure reason. So I'm curious to know if there is a way to cast/convert an stdClass object into a full fledged object of a given type.

For instance something along the lines of:

//$stdClass is an stdClass instance
$converted = (BusinessClass) $stdClass;

I am just casting the stdClass into an array and feed it to the BusinessClass constructor, but maybe there is a way to restore the initial class that I am not aware of.

Note: I am not interested in 'Change your storage system' type of answers since it is not the point of interest. Please consider it more an academic question on the language capacities.


Verified Answer (88 Votes)

07/14/2010 11:54:33

See the manual on Type Juggling on possible casts.

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.

Or, if you are in a hackish mood, you could adapt the following code:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        strstr(serialize($array), ':')

which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.

For object to object, the code would be

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        strstr(strstr(serialize($instance), '"'), ':')

Answer #2 (53 Votes)

03/22/2012 01:08:53

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);

Answer #3 (14 Votes)

01/21/2012 00:10:08

To move all existing properties of a stdClass to a new object of a specified class name:

 * recast stdClass object to an object with type
 * @param string $className
 * @param stdClass $object
 * @throws InvalidArgumentException
 * @return mixed new, typed object
function recast($className, stdClass &$object)
    if (!class_exists($className))
        throw new InvalidArgumentException(sprintf('Inexistant class %s.', $className));

    $new = new $className();

    foreach($object as $property => &$value)
        $new->$property = &$value;
    $object = (unset) $object;
    return $new;


$array = array('h','n');

$obj=new stdClass;
$obj->params= &$array;

class RestQuery{
    public $action;
    public $params=array();
    public $authKey='';

$restQuery = recast('RestQuery', $obj);

var_dump($restQuery, $obj);


object(RestQuery)#2 (3) {
  string(4) "auth"
  &array(2) {
    string(1) "h"
    string(1) "n"
  string(32) "865c0c0b4ab0e063e5caa3387c1a8741"

This is limited because of the new operator as it is unknown which parameters it would need. For your case probably fitting.

Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.