douhezhang8932 2013-04-25 15:21
浏览 46

too long

I have a Soap WebService that returns StdClass Object with different properties. What i want to do is to create a Mock Object that simulates the StdClass returned by WebService. What i dont want to do is to create the mock object manually. I dont want to serialize, unserialize the object because i want to maybe edit propertie values inside VCS.

So basically i need to turn this:

stdClass Object
(
    [paramA] => 1
    [paramB] => 2
    [paramC] => 3
    [paramD] => Array
    (
        [0] => stdClass Object
            (
                [paramD1] => 'blabla'
                [paramD2] => 'blabla'

into this:

$object = new stdClass;
$object -> paramA = 1;
$object -> paramB = 2;
$object -> paramC = 3;
$object -> paramD -> paramD1 = "blabla";
$object -> paramD -> paramD2 = "blabla";

How would you do it?

  • 写回答

1条回答 默认 最新

  • dounielong7728 2013-04-25 15:27
    关注

    A good way to quickly build stdClass objects is to cast an array to an object (outlined in Type Juggling):

    $object = (object) array('prop' => 'value');
    

    and as this shows, keys become property names and the values their values:

    echo $object->prop; # value
    

    This also works inside each other, like having an array of child objects:

    $object = (object) array(
        'prop'     => 'value',
        'children' => array(
            (object) array('prop' => 'value'),
        ),
    );
    

    Which will give you something along the lines like:

    echo $object->children[0]->prop; # value
    

    Which looks like that this is what you're looking for.

    See as well Convert Array to Object PHP for some more examples and variations.

    评论

报告相同问题?