- array_push: documentation ( source)
- strtok: documentation ( source)
- array_pop: documentation ( source)
<?php
class ExpressionCalculator {
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);
continue;
}
array_push($operands, $token);
}
return $result;
}
}
$calc = new ExpressionCalculator();
echo $calc->calc('5 1 2 + 4 * + 3 -'); // 14