3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php class ExpressionCalculator { private $operators = array( '+' => 'test', '-' => 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) in /in/ln3Dh on line 6
Process exited with code 255.
Output for 5.3.0 - 5.3.28
Parse error: syntax error, unexpected T_FUNCTION in /in/ln3Dh on line 6
Process exited with code 255.