You don't need any members for this at all since thing will need to persist. The 'x', 'y', and 'operator' setters are redundant since they are overwritten with any calculate call.
When doing OO code though, you may be better off using a composite model to write things like a calculator. It allows for extremely easy updating of functionality.
PHP Code:
<?php
interface ICalculation
{
public function calculate($lhs, $rhs);
}
class Calculator
{
public static function calculate($lhs, $rhs, ICalculation $fp)
{
return $fp->calculate($lhs, $rhs);
}
}
class CalculationAdd implements ICalculation
{
public function calculate($lhs, $rhs)
{
if (!is_numeric($lhs) || !is_numeric($rhs))
{
throw new Exception(NAN);
}
return $lhs + $rhs;
}
}
class CalculationSubtract implements ICalculation
{
public function calculate($lhs, $rhs)
{
if (!is_numeric($lhs) || !is_numeric($rhs))
{
throw new Exception(NAN);
}
return $lhs - $rhs;
}
}
class CalculationStringConcat implements ICalculation
{
public function calculate($lhs, $rhs)
{
return $lhs . $rhs;
}
}
// Usage
$a = 10;
$b = 5;
printf('$a + $b = %f' . PHP_EOL, Calculator::calculate($a, $b, new CalculationAdd()));
printf('$a - $b = %f' . PHP_EOL, Calculator::calculate($a, $b, new CalculationSubtract()));
try
{
printf('"cat" - "dog" = %f' . PHP_EOL, Calculator::calculate('cat', 'dog', new CalculationAdd()));
}
catch (Exception $ex)
{
print $ex->getMessage() . PHP_EOL;
}
printf('"cat" - "dog" = %s' . PHP_EOL, Calculator::calculate('cat', 'dog', new CalculationStringConcat()));
Validation is much much easier this way since its done at a per calculation basis. 'cat' + 'dog' using CalculateAdd will fail with a NAN, but 'cat' + 'dog' using a CalculateStringConcat will concat together. There is no end to the calculations you can do this way, but it is bound by a $lhs and $rhs only rule (which is fine anyway). All that needs to happen is a new class written to perform the calculation.