How to access a member of an stdClass in PHP

2019-03-02 02:16发布

问题:

I have a JSON object that I decoded, and I can't access the element because it throws an error.

stdClass Object
(
    [error] => InvalidRegistration
)

echo $device_response->error; // gives an error

How would I go about accessing attributes?

Below is whole array of response:

stdClass Object
(
    [multicast_id] => 5.3301797222004E+18
    [success] => 1
    [failure] => 3
    [canonical_ids] => 0
    [results] => Array
        (
            [0] => stdClass Object
                (
                    [message_id] => 0:1388910534147789%25796c83f9fd7ecd
                )

            [1] => stdClass Object
                (
                    [error] => InvalidRegistration
                )

            [2] => stdClass Object
                (
                    [error] => InvalidRegistration
                )

            [3] => stdClass Object
                (
                    [error] => InvalidRegistration
                )

        )

)

Below is how I am accessing it:

foreach ($responseBody->results as $device_response) {

        echo $device_response->error;

    }

回答1:

$obj = new stdClass();
$obj->foo = "var";
echo $obj->foo;