[英]php return inside switch case is working but return after switch is not working
Can anyone help me with the following function, why return
inside switch case is working (return correct converted price/quantity): 任何人都可以通过以下功能来帮助我,为什么
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, '.', '')];
}
}
But this one is not? 但是这个不是吗? (return only
case 136
converted price/quantity) ( return
after switch is not working) How can I improve from the above one, I want to use less code to do the above function, thanks! (仅返回
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, '.', '')];
}
Add the break;
添加
break;
statement at the end of each case
. 每个
case
末尾的陈述。 Otherwise the code of the next case
s of the switch
statement will be executed too. 否则,
switch
语句下一个case
的代码也将被执行。 Your return
statement uses variables that are defined in the switch
statement. 您的
return
语句使用switch
语句中定义的变量。 If somehow $unit_id
is not in the list of case
s, the return
will fail in error. 如果
$unit_id
不在case
s列表中,则return
将错误地失败。 To prevent the return
from failing, you could add this at the bottom of the case list: 为了防止
return
失败,您可以在案件列表的底部添加以下内容:
default: // $unit_id not found
return ['quantity' => '0.000', 'price' => '0.000']; // whatever you like
Or you could throw an Exception. 否则您可以抛出异常。
Return退出该函数,因此在您的情况下充当中断,这就是为什么它在第一种情况下起作用的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.