this is a simple problem, but i can’t figure it out;
‘op’ is a radio checkbox which has either */-+
if i echo it, it’s passing it fine.
$number1 = $_REQUEST['value1'];
$number2 = $_REQUEST['value2'];
$operator = $_REQUEST['op'];
[COLOR="Red"]$total = $number1 $operator $number2;[/COLOR]
if (empty($number1)){
echo "you have to set a number for the first field <br />";
}
if (empty($number2)){
echo "you have to set a number for the second field";
}
else{
echo "$number1 $operator $number2 = " . $total;
}
The simple switch is a fast way of doing things, however you can try the Strategy pattern for a more robust OOP way. It allows for more complex manipualtion if you need it later.
public interface IOperation
{
function Combine($first,$second);
}
/* create a class for each operation */
public class AddOperation implements IOPeration
{
function Combine($first,$second)
{
/* todo validate parameters */
return $first+$second;
}
}
/* .... Factory ... */
public class OperationFactory
{
public static function GetOperation($operator)
{
switch ($operator)
{
case "+": return new AddOperation();
/*todo the other operations */
default: throw new Exception("Operation not implented)";
}
}
}
/* in your controller */
$operation= OperationFactory::GetOperation($operator);
$result=$operation->Combine($value1,$value2);
Excuse my rusty php, it’s been a while since I’ve written any php code.