DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Simple Calculator in PHP (OOP principles)

So lets build a calculator which does the following.
1) Addition
2) Multiplication
3) Division
4) Subtraction

The folder and file structure is given below

Alt Text

Lets get the html index.php sorted first, so whats in it?


 include 'includes/';

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

<form action="includes/" method = "post">

    <p>Calculator V01</p>
    <input type= "number" name="num1" placeholder="First number">
    <select name="oper" >
      <option value="add"> Addition </option>
      <option value="sub"> Substraction </option>
      <option value="div">Division </option>
      <option value="mul">Multiplication </option>
    <input type="number" name="num2" placeholder="Second number">
    <button type="submit" name="submit">  Calculate</button>



The code above should be self-explanatory, if you are unsure about the class-autoload.php file have a look at this article( ) about it.

And here is the code we have in



function myAutoLoader($className){

    if(strpos($url, 'includes')!==false){
        $path = '../classes/';
        $path = 'classes/';
    $extension = '.class.php';
    require_once $path.$className.$extension;

Then we look at the calculator class file which is calc.class.php


class Calc{
    public $operator;
    public $num1;
    public $num2;

    public function __construct(string $one, int $two, int $three){
        $this->operator = $one;
        $this->num1 = $two;
        $this->num2 = $three;

    public function calculator(){
     switch ($this->operator) {
         case 'add':
            $result = $this->num1 + $this->num2;
            return $result;             
        case 'sub':
            $result = $this->num1 - $this->num2;
            return $result;             
        case 'div':    
             $result = $this->num1 / $this->num2;
             return $result;             
        case 'mul':    
             $result = $this->num1 * $this->num2;
             return $result;             



Then the next file is

include '';

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

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

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


When we load this up on xampp we can see the following.

Alt Text

I have created a small video on this

Top comments (3)

naveenkolambage profile image
Naveen Dinushka

Thanks heaps :)

macaronigrill profile image

Could you tell me what does im confused on that part

macaronigrill profile image

also how does it run, does it go from index.php to
how do the other files interact with those two?