douyanqu9722 2013-03-03 05:58
浏览 43
已采纳

三元操作返回“未定义属性”

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;
}
  • 写回答

1条回答 默认 最新

  • doumengwei0138 2013-03-03 06:04
    关注

    Don't nest ternary operator.

    You see the error because of the order in which ternary operators are evaluated; it would be far better and more maintainable to just write it out like this:

    if (isset($res->response)) {
      $error = $res->response->message;
    } elseif (isset($res->error)) {
      if (isset($res->error->message)) {
        $error = $res->error->message;
      } else {
        $error = $res->error;
      }
    } else {
      $error = $output;
    }
    

    Your old code evaluates like this; even then it's non-obvious what really happens:

    ((isset($res->response) ? $res->response->message :
    isset($res->error)) ? $res->error :
    isset($res->error->message)) ? $res->error->message :
    $output;
    

    See also: Comparison Operators

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料