doupin5667 2016-12-07 22:02
浏览 14
已采纳

PHP函数:如果设置了对象值,则返回它

I'm trying to output a value of on object, but the value might not exist for some object records. How do I return the value without raising error "Undefined property: stdClass"?

For example, I have an object:

$obj = '[{"id":111,"value1":1,"value2":2},{"id":111,"value1":1}]';

value2 does not exist for the second element in the array, and I want to write a function to process each object in the array. Example:

function add($obj){
   $sum = 0;
   foreach($obj as $o){
      $sum += $o->value1;          

       if(isset($o->value2)){
          $sum += $o->value2;
       }
   }
   return $sum;
}

The if part is what I want to improve. There might be dozens of other values that don't exist for some object. I don't want to write if(isset($o->valueN)) every time.

Is there any other easier ways to code this to avoid the undefined property error?

  • 写回答

2条回答 默认 最新

  • drlma06060 2016-12-07 22:08
    关注

    Option 1: In php7 you can use the Null Coalescing Operator,

    $sum += $o->value2 ?? 0;
    

    Option 2: If you can create specific classes for the sub-items, then you can use magic method __get() so you only need to write isset once.

    Option 3: Accept it? My code is littered with isset()s as it's a good reminder that something may or may not be set, but you know it and are handling it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀