3v4l.org

run code in 300+ PHP versions simultaneously
<?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(); while (($token = strtok($expression, ' ')) !== false) { 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:
39.74 ms | 402 KiB | 5 Q