You could also do as follows using object orientation, where all the complexity lies by responsibility of the class Calculator solve, thus making its use much easier, so much so when the future maintenance of the code.
<?php
class Calculator {
private $operator;
private $result;
public function __construct($value1)
{
$this->result = $value1;
}
public function calculate($operator, $value1)
{
switch ($operator) {
case '+':
$this->result += $value1;
break;
case '-':
$this->result -= $value1;
break;
case '/':
$this->result /= $value1;
break;
case '*':
$this->result *= $value1;
break;
case '%':
$this->result %= $value1;
break;
}
return $this;
}
public function getResult()
{
return $this->result;
}
}
Test of use of class Calculate:
<?php
require_once 'Calculator.php';
$calc = new Calculator(10);
echo $calc->calculate('+', 10)
->calculate('+', 10)
->getResult();//30
echo '<br>';
$calc1 = new Calculator(100);
echo $calc1->calculate('-', 10)->getResult();//90
echo '<br>';
$calc2 = new Calculator(2);
echo $calc2->calculate('*', 2)
->calculate('*', 2)
->getResult();//8
Some special reason you want to do this ?
– Edilson
Not really. It’s just that I’ve come across this situation a few times, and I’ve always used condition to accomplish this task. I wonder if there was something close to the format I quoted in the question.
– Thyago ThySofT
This smells like unnecessary stuff.. rsrs
– Daniel Omine