Skip to main content

Convert/cast an stdClass object to another class



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



Source: Tips4all

Comments

  1. 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 arrayToObject(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.

    For object to object, the code would be

    public static function objectToObject($instance, $className) {
    return unserialize(sprintf(
    'O:%d:"%s"%s',
    strlen($className),
    $className,
    strstr(strstr(serialize($instance), '"'), ':')
    ));
    }

    ReplyDelete
  2. 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;
    unset($object->$property);
    }
    unset($value);
    $object = (unset) $object;
    return $new;
    }


    Usage:

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

    $obj=new stdClass;
    $obj->action='auth';
    $obj->params= &$array;
    $obj->authKey=md5('i');

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

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

    var_dump($restQuery, $obj);


    Output:

    object(RestQuery)#2 (3) {
    ["action"]=>
    string(4) "auth"
    ["params"]=>
    &array(2) {
    [0]=>
    string(1) "h"
    [1]=>
    string(1) "n"
    }
    ["authKey"]=>
    string(32) "865c0c0b4ab0e063e5caa3387c1a8741"
    }
    NULL


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

    ReplyDelete
  3. 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);

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex