在PHP的if条件下执行

时间:2017-11-17 19:37:39

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

以下代码块抛出异常,即变量$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);

1 个答案:

答案 0 :(得分:-5)

您提供的两个代码片段,即抛出异常的代码片段和正在运行的代码片段不等效。第一个缺少布尔表达式$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);
    }