php返回内部交换机案例正在工作但在交换机不工作后返回

时间:2017-06-05 19:18:31

标签: php php-7

任何人都可以帮助我使用以下功能,为什么return内部切换工作正常(返回正确的转换价格/数量):

function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
            return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
    }
}

但这个不是吗? (仅返回case 136转换后的价格/数量)(切换后无效return)如何从上面的改进,我想用更少的代码来完成上述功能,谢谢!

function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
    switch ($unit_id) {
        case 8: // A Bushel
            $outQ = $quantity / $lbs_in_a_bu;
            $outP = $price * $lbs_in_a_bu;
        case 10: // Pounds
            $outQ = $quantity;
            $outP = $price;
        case 11: // CWT
            $outQ = $quantity / LBS_IN_CWT;
            $outP = $price * LBS_IN_CWT;
        case 12: // Metric Tonne
            $outQ = $quantity / LBS_IN_TON;
            $outP = $price * LBS_IN_TON;
        case 136: // W Bushel
            $outQ = $quantity / $lbs_in_w_bu;
            $outP = $price * $lbs_in_w_bu;
    }
    return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}

2 个答案:

答案 0 :(得分:3)

在每个break;的末尾添加case语句。否则,case语句的下一个switch的代码也将被执行。 您的return语句使用switch语句中定义的变量。如果某个$unit_id不在case列表中,则return将失败。为防止return失败,您可以在案例列表的底部添加:

default:  // $unit_id not found
  return ['quantity' => '0.000', 'price' => '0.000'];  // whatever you like

或者你可以抛出异常。

答案 1 :(得分:2)

返回退出函数,所以在你的情况下作为一个休息,这就是它在第一种情况下工作的原因。