Create a simple calculator with php OOP:
Create a file called calculator_view.php . Now paste the following code.
- <?php
require_once './classes/calculator.php';
$obj= new Calculator();
?>
<html>
<head>
<title>Loop Example</title>
</head>
<body>
<form action="calculator_view.php" method="post">
<table>
<tr>
<td>First Number </td>
<td>
<input type="text" name="first_number" value="<?php echo $_POST['first_number'];?>">
</td>
</tr>
<tr>
<td>Ending Number </td>
<td>
<input type="text" name="second_number" value="<?php echo $_POST['second_number'];?>">
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="btn" value="+">
<input type="submit" name="btn" value="-">
<input type="submit" name="btn" value="*">
<input type="submit" name="btn" value="/">
<input type="submit" name="btn" value="%">
</td>
</tr>
<?php
if(isset($_POST['btn']))
{
$first_number=$_POST['first_number'];
$second_number=$_POST['second_number'];
if($_POST['btn']=='+')
{
$result= $obj->add($first_number,$second_number);
}
if($_POST['btn']=='-')
{
$result= $obj->sub($first_number,$second_number);
}
if($_POST['btn']=='*')
{
$result= $obj->mul($first_number,$second_number);
}
if($_POST['btn']=='/')
{
$result= $obj->div($first_number,$second_number);
}
if($_POST['btn']=='%')
{
$result= $obj->rim($first_number,$second_number);
}
}
?>
<tr>
<td><?php echo $result['lbl'];?></td>
<td>
<?php echo $result['value'];?>
</td>
</tr>
</table>
</form>
</body>
</html>
Now create a folder called classes ,and create a file within the classes folder called calculator.php and paste the following code.
<?php
class Calculator{
function add($first_number,$second_number)
{ $result=array();
$result['value']=$first_number+$second_number;
$result['lbl']='Addition';
return $result;
}
function sub($first_number,$second_number)
{
$result=array();
$result['value']=$first_number-$second_number;
$result['lbl']='Subtruction';
return $result;
}
function mul($first_number,$second_number)
{
$result=array();
$result['value']=$first_number*$second_number;
$result['lbl']='Multiplication';
return $result;
}
function div($first_number,$second_number)
{
$result=array();
if($second_number==0)
{
$result='Undefine';
$result['lbl']='Divition';
return $result;
}
else{
$result=array();
$result['value']=$first_number/$second_number;
$result['lbl']='Divition';
return $result;
}
}
function rim($first_number,$second_number)
{
$result=array();
if($second_number==0)
{
$result='Undefine';
$result['lbl']='Reminder';
return $result;
}
else{
$result['value']=$first_number%$second_number;
$result['lbl']='Reminder';
return $result;
}
}
}
?>
0 comments:
Post a Comment