I have a simple calculator in php. And I am using the func_get_args for dynamically getting the values.
But the problem is with the multiply function.
So this is de code Calculator:
class Calculator
{
protected $result;
protected $operation;
public function setOperation(OperatorInterface $operation)
{
$this->operation = $operation;
}
public function calculate()
{
foreach (func_get_args() as $number) {
$this->result = $this->operation->run($number, $this->result);
}
}
public function getResult()
{
return $this->result;
}
}
Multiply
class Multiply implements OperatorInterface{
public function run($number, $result){
return $result * $number;
}
}
Index:
$sc = new Calculator();
$sc->setOperation(new Multiply);
$sc->calculate(10, 70);
echo $sc->getResult();
Because the result is 0. Because it starts with 0. But how to tackle this?
Thank you
interface:
interface OperatorInterface{
public function run($number, $result);
}
If I do it like this:
class Multiply implements OperatorInterface{
protected $result = 1;
public function run($number, $result){
return var_dump($result * $number);
}
}
and for exmample this:
$sc = new Calculator();
$sc->setOperation(new Multiply);
$sc->calculate(10, 70);
/*
$sc->setOperation(new Adder());
$sc->calculate(100, 70);
$sc->setOperation(new Subtractor);
$sc -> calculate(500);
*/
echo $sc->getResult();
it is still 0.
CodePudding user response:
When you instantiate the calculator, result is 0. So you are multiplying 0 * $number
which is always 0. You could set result to 1 in your Multiply class:
class Multiply implements OperatorInterface{
protected $result = 1;
public function run($number, $result){
return $result * $number;
}
}
CodePudding user response:
You are getting 0 because null * 10
give 0, after that you will get 0 * 70
which still results in 0.
Add the if statement to give a correct starting value:
class Multiply implements OperatorInterface{
public function run($number, $result){
if ($result === null) $result = 1;
return $result * $number;
}
}