//實現(xiàn)一個簡單的計算器
interface MathOp{
public function calculation($num1,$num2);
}
//加法
class MathAdd implements MathOp{
public function calculation($num1,$num2){
return $num1 + $num2;
}
}
//減法
class MathSub implements MathOp{
public function calculation($num1,$num2){
return $num1 - $num2;
}
}
//乘法
class MathMulti implements MathOp{
public function calculation($num1,$num2){
return $num1 * $num2;
}
}
//除法
class MathDiv implements MathOp{
public function calculation($num1,$num2){
return $num1 / $num2;
}
}
class Op{
protected $op_class = null;
public function __construct($op_type){
$this->op_class = 'Math' . $op_type;
}
public function get_result($num1,$num2){
$cls = new $this->op_class;
return $cls->calculation($num1,$num2);
}
}
$obj = new Op('Add');
echo $obj->get_result(6,2);//8
$obj = new Op('Sub');
echo $obj->get_result(6,5);//1
$obj = new Op('Multi');
echo $obj->get_result(6,2);//12
$obj = new Op('Div');
echo $obj->get_result(6,2);//3
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》