56

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.

3
  • 1
    Have you tried $obj->Title $obj->Color Oct 31, 2011 at 15:49
  • It would be a bit more insightful if you post the code snip that you are using to generate that output.
    – 0xd
    Oct 31, 2011 at 15:49
  • Wait, what? You have to "parse" a string? Or is this an actual object variable?
    – mario
    Oct 31, 2011 at 15:55

5 Answers 5

88

You can do: $obj->Title etcetera.

Or you can turn it into an array:

$array = get_object_vars($obj);
2
  • Thanks! $obj->Title does it for me.
    – dwarbi
    Oct 31, 2011 at 16:28
  • stdClass objects can have vars not accessible with the array notation. Example using the DB facade of laravel (using psysh): >>> $res = DB::select("show create table test")[0] >>> get_object_vars($res) [ "Table" => "test", "Create Table" => """ CREATE TABLE test (\n ... ] The "Create Table" var is only accessible using get_object_vars($res)
    – didier
    Jul 3, 2022 at 9:33
16

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

1
  • Thank you for your help! I just need $obj->Title, but good to know the other info for the future.
    – dwarbi
    Oct 31, 2011 at 16:29
8

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"
-1

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.

-1

extract(get_object_vars($obj))

will return $Title, $Color etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.