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

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

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C