Naveen Dinushka

Posted on

Simple Calculator in PHP (OOP principles)

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

The folder and file structure is given below

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

``````<?php

?>

<!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">
<title>Document</title>
<body>

<form action="includes/calc.inc.php" method = "post">

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

</form>

</body>
</html>
``````

And here is the code we have in class-autoload.inc.php

``````<?php

\$url= \$_SERVER['HTTP_HOST'].\$_SERVER['REQUEST_URI'];

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

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

``````<?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) {
\$result = \$this->num1 + \$this->num2;
return \$result;
break;
case 'sub':
\$result = \$this->num1 - \$this->num2;
return \$result;
break;
case 'div':
\$result = \$this->num1 / \$this->num2;
return \$result;
break;
case 'mul':
\$result = \$this->num1 * \$this->num2;
return \$result;
break;

}
}

}
``````

Then the next file is calc.inc.php

``````<?php

\$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.

I have created a small video on this https://youtu.be/lU23DLYte6w

Naveen Dinushka

Thanks heaps :)

MacaroniGrill

Could you tell me what calc.inc.php does im confused on that part

MacaroniGrill

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