Search code examples
phpstdclass

PHP stdClass Object with dot


I have a stdClass, that has an attribute with a dot in it's name. It's returned to me via an API, so there's nothing I can do with the name. It looks like this:

stdClass Object ( [GetPlayerResult] => stdClass Object ( [RegistrationResponses.Player] => Array (...)

Now, how do I access the array? When I do this:

print_r($result->GetPlayerResult->RegistrationResponses.Player);

it (obviously) prints just "Player". I have tried putting apostrophes around the last part, using [''] syntax (like an associative array), none of that works and throws a 500 error. Any ideas? Thanks!


Solution

  • You can try using braces:

    $object->GetPlayerResult->{"RegistrationResponses.Player"}
    

    Or you can cast it to an associative array

    $result = (array) $object->GetPlayerResult;
    $player = $result["RegistrationResponses.Player"];
    

    If you are parsing your website response using json_decode, note the existence of the second parameter to return as associative array:

    assoc

    When TRUE, returned objects will be converted into associative arrays.