DEV Community

Discussion on: Simple Calculator in PHP (OOP principles)

jorgecc profile image
Jorge Castro

Fine but let's me add a bit of code

class Calc{
    public $num1;
    public $num2;
    public function __construct(int $two, int $three){
        $this->num1 = $two;
        $this->num2 = $three;

class CalcService{
    // public $operator; // it is not required, this value has a short life.
    public static function calculator($operator,$calc){
     switch ($operator) {
         case 'add':
            $result = $calc->num1 + $calc->num2;
            return $result;             
        case 'sub':
            $result = $calc->num1 - $calc->num2;
            return $result;             
        case 'div':    
             $result = $calc->num1 / $calc->num2;
             return $result;             
        case 'mul':    
             $result = $calc->num1 * $calc->num2;
             return $result;             


Your original class usually is called the Business Object Class. It's a class that groups the fields and the logic (methods). While it works in the short run but it tends to fail in the long run (biggest projects).

So, our could be written as follow

include '';

$oper = $_POST["oper"];
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];

$calc = new Calc($num1,$num2);

try {
    echo CalculatorService($oper,$calc);
} catch (TypeError $e) {
    echo "Error!: " .$e->getMessage();


Why the change?

Let's say our code uses the database. So, if we have a class for the data and another class for the methods, then we could add a third service class for all methods that involve the database, for example, CalculatorRepo, CalculatorDao or CalculatorDAL.

i.e. we are doing SRP.

It is nothing special. For example, a Webservice is exactly a service class but shared via web. Our first class (Calc) usually is called the MODEL.

Even more, we could do a method that fetches ($_POST) the values from the post and creates the model Calc (if the information is right).

naveenkolambage profile image
Naveen Dinushka Author

Thanks heaps :)