How do I get the value from object(stdClass)?

PhpParsing

Php Problem Overview


Using PHP, I have to parse a string coming to my code in a format like this:

object(stdClass)(4) { 
    ["Title"]=> string(5) "Fruit" 
    ["Color"]=> string(6) "yellow" 
    ["Name"]=> string(6) "banana" 
    ["id"]=> int(3) 
}

I'm sure there's a simple solution, but I can't seem to find it... how to get the Color and Name?

Thanks so much.

Php Solutions


Solution 1 - Php

You can do: $obj->Title etcetera.

Or you can turn it into an array:

$array = get_object_vars($obj);

Solution 2 - Php

You create StdClass objects and access methods from them like so:

$obj = new StdClass;

$obj->foo = "bar";
echo $obj->foo;

I recommend subclassing StdClass or creating your own generic class so you can provide your own methods.

Turning a StdClass object into an array:

You can do this using the following code:

$array = get_object_vars($obj);

Take a look at: http://php.net/manual/en/language.oop5.magic.php http://krisjordan.com/dynamic-properties-in-php-with-stdclass

Solution 3 - Php

Example StdClass Object:

$obj = new stdClass();

$obj->foo = "bar";

By Property (as other's have mentioned)

echo $obj->foo; // -> "bar"

By variable's value:

$my_foo = 'foo';

echo $obj->{$my_foo}; // -> "bar"

Solution 4 - Php

I have resolved this issue by converting stdClass object to array using json_encode and json_decode like this:

$object_encoded = json_encode( $obj );
$object_decoded = json_decode( $object_encoded, true );

echo $object_decoded['Color'];

Note: passing true parameter in json_decode will return an associative array.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondwarbiView Question on Stackoverflow
Solution 1 - PhpNaftaliView Answer on Stackoverflow
Solution 2 - Phpuser542603View Answer on Stackoverflow
Solution 3 - PhpmfinkView Answer on Stackoverflow
Solution 4 - PhpTayyab ChaudharyView Answer on Stackoverflow