标签:io ar sp cti on c new res r
采用封装方式 <?php class Calc{ /** * 计算结果 * * @param int|float $num1 * @param int|float $num2 * @param string $operator * @return int|float */ public function calculate($num1,$num2,$operator){ try { $result=0; switch ($operator){ case ‘+‘: $result= $num1+$num2; break; case ‘-‘: $result= $num1-$num2; break; case ‘*‘: $result= $num1*$num2; break; case ‘/‘: if ($num2==0) { throw new Exception("除数不能为0"); } $result= $num1/$num2; break; } return $result; }catch (Exception $e){ echo "您输入有误:".$e->getMessage(); } } } $test=new Calc(); // echo $test->calculate(2,3,‘+‘);//打印:5 echo $test->calculate(5,0,‘/‘);//打印:您输入有误:除数不能为0 ?>
标签:io ar sp cti on c new res r
原文地址:http://my.oschina.net/xinson/blog/312899