• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[Release] [PHP] [OOP] Calculator

Elite Diviner
Joined
Jul 25, 2013
Messages
466
Reaction score
55
Hello everyone, I was practicing OOP PHP, and I ended up with an OOP PHP Calculator! So here is the source:

Code:
<?php
class Calculater {
	public function add($num1, $num2) {
		$total = $num1 + $num2;
		echo $total;
	}
	public function substract($num1, $num2) {
		$total = $num1 - $num2;
		echo $total;
	}
	public function multiply($num1, $num2) {
		$total = $num1 * $num2;
		echo $total;
	}
	public function divide($num1, $num2) {
		$total = $num1 / $num2;
		echo $total;
	}
}
$Calculate = new Calculater;
if(isset($_REQUEST['submit'])) {
	$num1 = $_POST['num1'];
	$num2 = $_POST['num2'];
	if(!ctype_digit($num1)) {
		echo "Error: Your inputs may only contain numbers";
		exit();
	}
	if(!ctype_digit($num2)) {
		echo "Error: Your inputs may only contain numbers";
		exit();
	}
	$operation = $_POST['operation'];
	if($operation == "Add") {
		$Calculate->add($num1, $num2);
	}
	if($operation == "Substract") {
		$Calculate->substract($num1, $num2);
	}
	if($operation == "Multiply") {
		$Calculate->multiply($num1, $num2);
	}
	if($operation == "Divide") {
		$Calculate->divide($num1, $num2);
	}
}
?>
<form method="post" action="" name="submit">
<input type="text" name="num1">
<input type="text" name="num2">
<select name="operation">
	<option>Add</option>
	<option>Substract</option>
	<option>Multiply</option>
	<option>Divide</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>

Copy paste the above code in a *.php file and save it. In-order to run it you need an Apache server. Hope you like the release! Please give me ideas to release something the next time because I am always looking to code something and release it! Please give me feed back if you have ideas on improving my code!
 
Pee Aitch Pee
Joined
Mar 30, 2011
Messages
630
Reaction score
422
- I don't really see how this is OOP, you only created a class with 4 functions.
- You have to return in functions, not echo values.
- $_REQUEST > $_POST.
- Switch statement for the operation part may look neater.
- Your <option>'s do not have any value bound to it. (<option value="add">).

Make it so that I can do multiple calculations at once, instead of making it possible to add/subtract/multiply/divide 2 values only.
 
Experienced Elementalist
Joined
Jul 23, 2012
Messages
201
Reaction score
128