commit existing workshops
This commit is contained in:
50
workshop5/Models/Calculator.php
Normal file
50
workshop5/Models/Calculator.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
class Calculator
|
||||
{
|
||||
/*
|
||||
* Class for calculating 2 numbers
|
||||
*/
|
||||
var $expression;
|
||||
|
||||
/*
|
||||
* Constructor takes 2 numbers and an operator
|
||||
* @param int $number Number to be converted
|
||||
* @param string $unit Conversion unit
|
||||
*/
|
||||
public function __construct($expression = '')
|
||||
{
|
||||
$this->expression = $expression;
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculates number and returns result
|
||||
* @return string Result of calculation
|
||||
*/
|
||||
public function calculate(): string
|
||||
{
|
||||
$result = false;
|
||||
$this->expression = preg_replace('/\s+/', '', $this->expression);
|
||||
if(preg_match('/(\d+)([x\*\-\+\/])(\d+)/', $this->expression, $matches)) {
|
||||
$number1 = $matches[1];
|
||||
$operator = $matches[2];
|
||||
$number2 = $matches[3];
|
||||
if (is_numeric($number1) && is_numeric($number2)) {
|
||||
switch ($operator) {
|
||||
case '+':
|
||||
$result = ($number1 + $number2);
|
||||
break;
|
||||
case '-':
|
||||
$result = ($number1 - $number2);
|
||||
break;
|
||||
case '*':
|
||||
case 'x':
|
||||
$result = ($number1 * $number2);
|
||||
break;
|
||||
case '/':
|
||||
$result = ($number1 / $number2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} return $result;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user