PHP的回报是工作,但开关后返回工作不

问题描述:

谁能帮我用下面的函数,为什么return内部开关的情况下工作(返回正确的换算价格/数量):PHP的回报是工作,但开关后返回工作不

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, '.', '')]; 
} 
+3

是你在你切换语句的情况下“打破”的意外吗?不管$ unit_id的值如何,情况136都将最后一次运行。 – victor

+0

@victor哦权利哇。我以前总是使用退货,忘记了我需要使用休息。谢谢! –

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

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

或者你可以抛出一个异常。

+0

是的,因为我一直都在用return,忘记我要用break,谢谢! –

+0

这是def首先跳到我身上,但如何影响return语句不运行? – victor

+0

@ Code4R7实际上是最后一个被执行...... hm –

返回退出函数,因此在您的情况下充当休息,这就是为什么它在第一种情况下工作。

+0

感谢您的帮助! –