<?php
class ExpressionCalculator {
private $operators = array(
function ($leftOperand, $rightOperand) {
return $leftOperand + $rightOperand;
},
function ($leftOperand, $rightOperand) {
return $leftOperand - $rightOperand;
},
function ($leftOperand, $rightOperand) {
return $leftOperand * $rightOperand;
},
function ($leftOperand, $rightOperand) {
return $leftOperand / $rightOperand;
}
);
public function calc($expression) {
$operands = array();
while (($token = strtok($expression, ' ')) !== false) {
if (isOperator($token)) {
$rightOperand = array_pop($operands);
$leftOperand = array_pop($operands);
$result = $this->execute($token, $leftOperand, $rightOperand);
array_push($operands, $result);
} else if (is_numeric($token)) {
array_push($operands, $token);
} else {
throw new InvalidArgumentException('Expression has invalid token: ' + $token);
}
}
return $result;
}
private function isOperator($token) {
return isset($operators[$token]);
}
private function execute($operator, $leftOperand, $rightOperand) {
return call_user_func($operators[$operator], $leftOperand, $rightOperand);
}
}
$calc = new ExpressionCalculator();
echo $calc->calc('5 1 2 + 4 * + 3 -'); // 14
- Output for 5.4.0 - 5.4.24
- Parse error: syntax error, unexpected 'function' (T_FUNCTION), expecting ')' in /in/8XLge on line 5
Process exited with code 255. - Output for 5.3.0 - 5.3.28
- Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in /in/8XLge on line 5
Process exited with code 255.
preferences:
171.98 ms | 1395 KiB | 61 Q