Skip to content

Instantly share code, notes, and snippets.

@ReinierC
Last active May 9, 2024 10:38
Show Gist options
  • Save ReinierC/33798ad6ddb29d0e7772279ee1ebaa62 to your computer and use it in GitHub Desktop.
Save ReinierC/33798ad6ddb29d0e7772279ee1ebaa62 to your computer and use it in GitHub Desktop.
PHP OOP Calculator
<?php
class Calc {
public $num1;
public $num2;
public $cal;
public function __construct($num1Inserted, $num2Inserted, $calInserted) {
$this->num1 = $num1Inserted;
$this->num2 = $num2Inserted;
$this->cal = $calInserted;
}
public function calcMethod() {
switch ($this->cal) {
case 'add':
$result = $this->num1 + $this->num2;
break;
case 'sub':
$result = $this->num1 - $this->num2;
break;
case 'mul':
$result = $this->num1 * $this->num2;
break;
default:
$result = "Error";
break;
}
return $result;
}
}
?>
<?php
include 'calc.inc.php';
$num1 = $_POST['num1Inserted'];
$num2 = $_POST['num2Inserted'];
$cal = $_POST['calInserted'];
$calculator = new Calc($num1, $num2, $cal);
echo $calculator->calcMethod();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Calculator</title>
<style>
p {
font-size: 12px;
}
.alert {
color: red;
}
</style>
</head>
<body>
<h2>OOP calculator</h2>
<br>
<form action="calc.php" method="POST">
<input type="text" name="num1Inserted">
<input type="text" name="num2Inserted">
<select name="calInserted">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
</select>
<button type="submit">Calculate</button>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment