<?php abstract class Operation { public numA = 0; public numB = 0; public function __construct($numA, $numB) { $this->numA = $numA; $this->numB = $numB; } abstract function getResult(); } class OperationAdd extends Operation { public function getResult() { return numA+numB; } } class OperationSub extends Operation { public function getResult() { return numA - numB; } } class OperationMul extends Operation { public function getResult() { return numA * numB; } } class OperationDiv extends Operation { public function getResult() { if(numB == 0) { throw new Exception("除数不能为 0 。"); } return (double) (numA / numB); } } /** *************************************** */ // 简单运算工厂类 class OperationFactory { public static createOperate($operation, $numA, $numB) { switch($operation) { case '+': $oper = new OperationAdd($numA, $numB); break; case '-': $oper = new OperationSub($numA, $numB); break; case '*': $oper = new OperationMul($numA, $numB); break; case '/': $oper = new OperationDiv($numA, $numB); break; } return $oper; } } /** ************************ */ // 调用方式 $numA = 100; $numB = 8; $operation = '+'; $oper = OperationFactory::createOperate($operation, $numA, $numB); echo $oper.getResult();