views:

48

answers:

1

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:

//$std_class 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.

Cheers

+3  A: 

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:

public static function castToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        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.

Gordon
This hack is a clever technique. Won't be using it since my current way of solving the issue is more stable, but interesting nonetheless.
Guillaume Bodi