[英]php return inside switch case is working but return after switch is not working
任何人都可以通過以下功能來幫助我,為什么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, '.', '')];
}
添加break;
每個case
末尾的陳述。 否則, switch
語句下一個case
的代碼也將被執行。 您的return
語句使用switch
語句中定義的變量。 如果$unit_id
不在case
s列表中,則return
將錯誤地失敗。 為了防止return
失敗,您可以在案件列表的底部添加以下內容:
default: // $unit_id not found
return ['quantity' => '0.000', 'price' => '0.000']; // whatever you like
否則您可以拋出異常。
Return退出該函數,因此在您的情況下充當中斷,這就是為什么它在第一種情況下起作用的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.