Simple calculator class
by Reece

Simple calculator class

Last updated on June 15th, 2015 by Reece in Web Development

php

Here is a simple calculator class I wrote before. Make sure to validate and sanitize the value of x, y & mode if you want to use this in production. 🙂


class Calc {

private $_x;
private $_y;
private $_mde;

public function __construct($xVal, $yVal, $modeVal) {
   $this->_x = $xVal;
   $this->_y = $yVal;
   $this->_mde = $modeVal;
}

public function __toString() {
   return $this->mthd($this->_x, $this->_y, $this->_mde);
}

public function mthd($x, $y, $mode) {

   switch ($mode) {
      case '+':

         $sum = $x + $y;
         return "{$sum}";
         break;

      case '-':

         $diff = $x - $y;
         return "{$diff}";
         break;

      case '*':

         $prod = $x * $y;
         return "{$prod}";
         break;

      case '/':

         $quot = $x / $y;
         return "{$qout}";
         break;

      default:
         return("Please put a method!");
         break;
      }
   }
}

Comments

comments