Index.php →
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="calc.php" method="post">
<input type="text" name="num1" value="">
<input type="text" name="num2" value="">
<select name="cal">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
</select>
<button type="submit">Calculate</button>
</form>
</body>
</html>
calc.php →
<?php
include 'includes/calc.inc.php';
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$cal = $_POST['cal'];
$calculator = new Calc($num1, $num2, $cal);
echo $calculator->calcMethod();
calc.inc.php →
class Calc {
public $num1;
public $num2;
public $cal;
public function __construct($num1, $num2, $cal) {
$this->num1 = $num1;
$this->num2 = $num2;
$this->cal = $cal;
}
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";
# code...
break;
}
return $result;
}
}
I have a couple of questions to understand OOP’s better through this solid example.
This is the snippet from calc.inc.php →
public $num1;
public $num2;
public $cal;
public function __construct($num1, $num2, $cal) {
$this->num1 = $num1;
$this->num2 = $num2;
$this->cal = $cal;
}
This is the snippet from calc.php →
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$cal = $_POST['cal'];
$num1, for example is same in both the calc.php and calc.inc.php or these would have been a different named variable still the programme would have been working?