首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >php在交换机内部的返回是工作的,但是在开关不工作后返回

php在交换机内部的返回是工作的,但是在开关不工作后返回
EN

Stack Overflow用户
提问于 2017-06-05 19:18:31
回答 2查看 1.1K关注 0票数 1

谁能帮我完成以下功能,为什么return在开关箱内工作(返回正确的转换价格/数量):

代码语言:javascript
复制
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)我如何从上面的一个改进,我想用较少的代码来做上述功能,谢谢!

代码语言:javascript
复制
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, '.', '')];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-05 19:20:35

在每个break;语句的末尾添加case语句。否则,switch语句的下一个switch的代码也将被执行。return语句使用在switch语句中定义的变量。如果$unit_id没有出现在case的列表中,那么return就会出错。为了防止return失败,可以在案例列表的底部添加以下内容:

代码语言:javascript
复制
default:  // $unit_id not found
  return ['quantity' => '0.000', 'price' => '0.000'];  // whatever you like

或者你可以抛出一个例外。

票数 3
EN

Stack Overflow用户

发布于 2017-06-05 19:22:08

返回退出函数,因此在您的情况下充当中断,这就是它在第一种情况下工作的原因。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44376147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档