三元忽略第一个条件
Ternary ignores first condition
为什么我的三元组忽略了第一个条件 ($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 ');
您需要对括号中的每个下一个表达式进行分组,如下所示。您忘记将第二个三元表达式括在括号中。
$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 ');
但是无论如何你应该避免这种方法。
对订单状态做出反应的更好方法是switch statement。像这样:
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;
}
很容易看出如何扩展它以对其他状态词做出反应。
请注意,我将 `"prepairing" 更改为 "preparing"。
程序员追求的一件事就是简洁的代码。然而,更短的代码并不总是更好的代码。它可能不太可读并且更难维护和扩展。
为什么我的三元组忽略了第一个条件 ($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 ');
您需要对括号中的每个下一个表达式进行分组,如下所示。您忘记将第二个三元表达式括在括号中。
$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 ');
但是无论如何你应该避免这种方法。
对订单状态做出反应的更好方法是switch statement。像这样:
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;
}
很容易看出如何扩展它以对其他状态词做出反应。
请注意,我将 `"prepairing" 更改为 "preparing"。
程序员追求的一件事就是简洁的代码。然而,更短的代码并不总是更好的代码。它可能不太可读并且更难维护和扩展。