使用PHP match case实现逻辑时遇UnhandledMatchError问题求助
解决PHP match case未处理匹配错误的方案
错误原因
你当前的match用法存在逻辑错误:PHP的match表达式是将匹配值(此处为$cart对象)与每个分支的条件值做严格相等比较。你写的!is_null($cart->product_id)返回布尔值,和$cart(Cart模型实例)永远不可能严格相等,导致所有分支都不匹配,触发UnhandledMatchError。
优先方案:修正match case用法
将match的匹配值改为true,让分支的布尔条件直接匹配,同时必须添加default分支处理边界情况:
function increaseQuantity($data, $cart){ try { $user = Auth::user(); $data = match(true){ !is_null($cart->product_id) => $this->checkProductQuantityInStore($cart), !is_null($cart->meal_plan_id) => $this->checkMealPlanQuantityInStore($cart), default => null, // 处理既无product_id也无meal_plan_id的情况 }; if($data){ return $data; } return $user->carts()->where('id', $cart->id)->increment('quantity', $data['quantity'] ?? 1); } catch (\Throwable $th) { throw $th; } }
替代方案:if/switch语句
如果不想用match,也可以用更直观的if或switch实现:
if版本
function increaseQuantity($data, $cart){ try { $user = Auth::user(); if(!is_null($cart->product_id)){ $data = $this->checkProductQuantityInStore($cart); } elseif(!is_null($cart->meal_plan_id)){ $data = $this->checkMealPlanQuantityInStore($cart); } else { $data = null; } if($data){ return $data; } return $user->carts()->where('id', $cart->id)->increment('quantity', $data['quantity'] ?? 1); } catch (\Throwable $th) { throw $th; } }
switch版本
function increaseQuantity($data, $cart){ try { $user = Auth::user(); switch(true){ case !is_null($cart->product_id): $data = $this->checkProductQuantityInStore($cart); break; case !is_null($cart->meal_plan_id): $data = $this->checkMealPlanQuantityInStore($cart); break; default: $data = null; break; } if($data){ return $data; } return $user->carts()->where('id', $cart->id)->increment('quantity', $data['quantity'] ?? 1); } catch (\Throwable $th) { throw $th; } }
内容的提问来源于stack exchange,提问作者Abhay
相关产品推荐
相关产品推荐

