I have switched from using this ternary operation to if/elseif/else, but I would really like to know why this doesn't work. I keep getting the error:
ErrorException [ Notice ]: Undefined property: stdClass::$error
If I were to switch the order of the conditions so that the $res->response
piece was 3rd, then I get the same error but for that property instead. It makes no sense to me, and testing it on Codepad.org (which uses PHP 5.2) it works as expected: http://codepad.org/gwteijIe
Here's the test code in question:
$output = '{"error":{"message":"This is a test error"}}';
$res = json_decode($output);
$error = isset($res->response) ? $res->response->message :
isset($res->error) ? $res->error :
isset($res->error->message) ? $res->error->message :
$output;
echo $error;
(The reason why it checks for $res->error
and $res->error->message
is because the API we're using will return any one of the three conditions we're checking for. Disclaimer: it's not my API!)
Any insight as to why I am not getting the results I expect? Many thanks in advance for the help.
Edit:
To clarify, this is what I am trying to achieve:
if (isset($res->response))
{
$error = $res->response->message;
}
elseif (isset($res->error->message))
{
$error = $res->error->message;
}
elseif (isset($res->error))
{
$error = $res->error;
}