为什么我的三元忽略第一个条件($order->status === "prepairing")?检查订单状态时,它总是跳过第一个条件并立即进入第二个条件(并且始终将其视为真)$messageMiddle = ( ($order->status === "prepairing") ? " your prder is being prepared. Make your way towards the store."
: ($order->status === "complete") ?' your order is done! Please show your order-code at the store.'
: ' thank you for ordering ');
2 回答
jeck猫
TA贡献1909条经验 获得超7个赞
您需要按如下方式将括号中的每个下一个表达式分组。您忘记将第二个三元表达式括在括号中。
$messageMiddle = ($order->status === "prepairing") ? " your order is being prepared. Make your way towards the store." : (($order->status === "complete") ? ' your order is done! Please show your order-code at the store.' : ' thank you for ordering ');
但无论如何你都应该避免这种方法。
子衿沉夜
TA贡献1828条经验 获得超3个赞
对订单状态做出反应的更好方法是使用switch 语句。像这样:
switch ($order->status) {
case "preparing" : $messageMiddle = " your order is being prepared. Make your way towards the store.";
break;
case "complete" : $messageMiddle = " your order is done! Please show your order-code at the store.";
break;
default : $messageMiddle = " thank you for ordering ";
break;
}
很容易看出如何扩展它以对其他状态词做出反应。
请注意,我将“准备”更改为“准备”。
程序员追求的目标之一是简洁的代码。然而,较短的代码并不总是更好的代码。它可能可读性较差,并且更难以维护和扩展。
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报
0/150
提交
取消