Here is a solution.
It works on the basis that add()
or subtract()
doesn't directly carry out any work, it simply sets a "pending" operation, and that one()
or two()
(I've shortcut that style to key($num)
for simplicity though, I think it's better and more flexible as well) actually does the the last operation specified by add()
or subtract()
, using the number specified in the input.
It works by using PHP's ability to specify a function to call using a string value. Bit hacky but it seems to work.
class Calculator
{
private $result;
private $nextOp;
function __construct()
{
$this->result = 0;
$this->nextOp = "addVal";
}
function key($num)
{
$this->{$this->nextOp}($num);
return $this;
}
function add()
{
$this->nextOp = "addVal";
return $this;
}
function subtract()
{
$this->nextOp = "subtractVal";
return $this;
}
private function addVal($num)
{
$this->result += $num;
}
private function subtractVal($num)
{
$this->result -= $num;
}
function result()
{
return $this->result;
}
}
$test = new Calculator();
$a = $test->key(1)->add()->key(2)->key(3)->subtract()->key(2)->result();
var_dump($a);
This outputs 4
.
N.B. It assumes that if you wrote e.g. key(1)->add()->key(2)->key(2)
the second call to key(2)
would also do an add
, because that was the last operation specified (so the result would be 5
in that case), and also the initial operation is always add
as well (although I guess you could allow that to be specified in the constructor). I don't know if these assumptions are acceptable in your scenario, you didn't specify what should happen if the user write something like this, or what the class should do with the initial value.
Live demo: http://sandbox.onlinephpfunctions.com/code/0be629f803261c35017ae49a51fa24385978568d