【问题标题】:under the hood execution of if condition in PHP [duplicate]在 PHP 中执行 if 条件 [重复]
【发布时间】:2017-11-17 19:37:38
【问题描述】:

下面的代码块会引发变量$booking 未定义的异常。有人能解释一下为什么吗?

if(
     trim($request->id)!='' 
     && $booking = Booking::find($request->id) 
     && $booking->user_id == auth()->user()->id // undefined variable $booking
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }

但是这没有任何问题

if(
    trim($request->id)!='' 
    && $booking = Booking::find($request->id)
    ) {
      if($booking->user_id == auth()->user()->id)
                    return response()->json($booking);
}
return response()->json(['message' => 'not found'],404);

【问题讨论】:

  • 看看operator precedence$booking = Booking::find($request->id) 周围需要括号,因为分配的优先级较低。
  • @jh1711 是正确的。 3v4l.org/udBtn 另外,您应该真正使用严格比较 !== '',因为空字符串被 PHP 认为是“false-y”,并且大致等同于许多其他不同类型的 false-y 事物。

标签: php if-statement logical-operators php-7.1


【解决方案1】:

您提供的两个代码片段,一个是抛出异常的,一个是工作的,是不等价的。第一个缺少布尔表达式$booking->user_id != null。 Probalby,你应该编码:

if(
     trim($request->id)!='' 
     && $booking = Booking::find($request->id) 
     && $booking->user_id != null               // added stuff here
     && $booking->user_id == auth()->user()->id // $booking no more undefined 
       ) {
          return response()->json($booking);
    }
    else {
          return response()->json(['message' => 'not found'],404);
    }

【讨论】:

  • 这会抛出同样的错误。您尝试在分配之前访问 $booking->user_id。
  • 它也可以在没有 $booking->user_id != null 的情况下工作。无论如何我更新了问题
猜你喜欢
  • 2011-05-19
  • 2014-07-18
  • 1970-01-01
  • 2014-06-29
  • 2020-12-10
  • 2017-11-08
  • 2013-03-05
  • 2015-03-04
  • 1970-01-01
相关资源
最近更新 更多