0

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?

Timur
  • 639
  • 6
  • 21

1 Answers1

1

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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Sorry, not really what i want. I want to "parse" object one time and save the output as object definition. – Timur Apr 26 '13 at 09:03
  • You might be looking for something called serialization: http://php.net/language.oop5.serialization – hakre Apr 26 '13 at 09:24
  • "I dont want to serialize, unserialize the object because i want to maybe edit propertie values inside VCS." or do you have any ideas how i can turn serialized object into object definition? – Timur Apr 26 '13 at 12:29
  • Uhm, well, serialzation is for storing. So to say to put an object "off-line" (program not running) and back online again. If you also need to edit the serialized format - you write VCS - you probably mean by using a text-editor? Because objects serialized with `serialize()` can just be edited as well with a PHP script that is unserializing them, modifying the online object and serializing again. Another way in PHP that is similar simple to serialize/unserialize is to use `var_export` to write and `include` with the `return` statement to pull it back in. You save a PHP file you can edit then. – hakre Apr 26 '13 at 13:13
  • An example of that is here: http://blog.elijaa.org/index.php?post/2010/06/22/Handle-configuration-in-PHP-with-var_export() - just you can probably better understand what I just commented about `var_export`. – hakre Apr 26 '13 at 13:14