Simple basic calculator php class I wrote this basic calculator class using php.It will only execute the basic arithmetics operations so any suggestion for new functions add and improvements will be accepted. Thank you.

&lt;?php

class Calculator{

public $x , $y , $z;    

    public function __construct($x,$y,$z){
        $this-&gt;x = $x;
        $this-&gt;y = $y;
        $this-&gt;z = $z;
    }

    public function calc(){
        try{
            if($this-&gt;x != 0 &amp;&amp; $this-&gt;z != 0){

                switch($this-&gt;y){
                case '+': 
                return ($this-&gt;x + $this-&gt;z); 
                break;

                case '-':
                return ($this-&gt;x - $this-&gt;z);
                break;

                case '/':
                return ($this-&gt;x / $this-&gt;z);
                break;    

                case '*':
                return ($this-&gt;x * $this-&gt;z);
                break;

                } 
            } else {

                throw new Exception('Operations with 0 not alloewd!'); 

            }    
        } 
        catch(Exception $e){
            return $e-&gt;getMessage();    
        }
    }    
}
?&gt;
Im not going to comment on the implementation of the calculator (there are more well versed people out there) but I will comment on the coding style;

Return early (or in this case throw early)

I much prefer (I think most people do) to return or throw early to avoid more brackets and indentation. 

So I would change the body of calc() to look like; 

if($this-&gt;x == 0 &amp;&amp; $this-&gt;z == 0){
    throw new \Exception('Operations with 0 not allowed!');             
}

switch($this-&gt;y){
    case '+': 
    return ($this-&gt;x + $this-&gt;z); 
    break;

    case '-':
    return ($this-&gt;x - $this-&gt;z);
    break;

    case '/':
    return ($this-&gt;x / $this-&gt;z);
    break;    

    case '*':
    return ($this-&gt;x * $this-&gt;z);
    break;

    default: 
    throw new \Exception('Unknown operator');
    break;

}


Let Exceptions bubble up

If this is a calculator the excepted return is a number, not a string so doing the whole try catch and returning the $e-&gt;getMessage() is probably not what the developer expects to happen. 

Variables In The Constructor

There is a lot of resources out there that suggest this is the correct way to pass data to a class.

To me variables passed to a constructor should be other classes this class depends on, the reason is so we don't have to add more manual definitions when using dependency injection (this is not true in every instance). 

but here are some arguments why in this particular instance I wouldn't pass data to the constructor 


For dependency injection you are going to have to define where those variables are
You will have to instantiate a new Calculator(x, y, z) every time you want to use it which seems wasteful as you return the values and not store them for another class to use