Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Advanced Calulator Inheritance

Aim:
To implement the inheritance concept using PHP.

Algorithm:
STEP 1: Start the process.
STEP 2 :create a php file named "calculator.php".
STEP 3: design the page using text box,drop downlist and a
button.
STEP 4: Create a class calculator.
STEP 5: Create two variables num1,num2.
STEP 6: Define a method calculate that has basic operations like
addition,subraction,multiplication and division.
STEP 7:Create another class AdvancedCalculator that extends
the calculator class.
STEP 8:Define a method that calculates the power value of a
number.
STEP 9:save and run the file.
STEP 10:stop the process.

Program:

<!DOCTYPE html>
<html>
<head>
<title>Advanced Calculator</title>
</head>
<body>
<h1>Advanced Calculator</h1>
<form method="post" action="">
<input type="number" name="num1" placeholder="Enter
number 1" required>
<select name="operator">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
<option value="power">^</option>
</select>
<input type="number" name="num2" placeholder="Enter
number 2" required>
<input type="submit" value="Calculate">
</form>
<?php
class Calculator {
protected $num1;
protected $num2;

public function __construct($num1, $num2) {


$this->num1 = $num1;
$this->num2 = $num2;
}

public function calculate($operator) {


switch ($operator) {
case "add":
return $this->num1 + $this->num2;
case "subtract":
return $this->num1 - $this->num2;
case "multiply":
return $this->num1 * $this->num2;
case "divide":
if ($this->num2 != 0) {
return $this->num1 / $this->num2;
} else {
return "Cannot divide by zero";
}
default:
return "Invalid operator";
}
}
}

class AdvancedCalculator extends Calculator {


public function calculate($operator) {
if ($operator === "power") {
return pow($this->num1, $this->num2);
} else {
// Call the parent class's calculate method for other
operators
return parent::calculate($operator);
}
}
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$operator = $_POST["operator"];

$calculator = new AdvancedCalculator($num1, $num2);


$result = $calculator->calculate($operator);
echo "<p>Result: $result</p>";
}
?>
</body>
</html>

OUTPUT:

Result:
Thus the program has been executed successfully.

You might also like