<?php
class ExpressionCalculator {
private $operators = array();
public function __construct() {
$operators['+'] = function ($leftOperand, $rightOperand) {
return $leftOperand + $rightOperand;
};
$operators['-'] = function ($leftOperand, $rightOperand) {
return $leftOperand - $rightOperand;
};
$operators['*'] = function ($leftOperand, $rightOperand) {
return $leftOperand * $rightOperand;
};
$operators['/'] = function ($leftOperand, $rightOperand) {
return $leftOperand / $rightOperand;
};
}
public function calc($expression) {
$operands = array();
$i = 0;
while (($token = strtok($expression, ' ')) !== false) {
echo $token;
$i++;
if ($i > 100) {
die;
}
if ($this->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
preferences:
35.09 ms | 402 KiB | 5 Q