3v4l.org

run code in 300+ PHP versions simultaneously
<?php class ExpressionCalculator { private $operators = array(); public __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 (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 '__construct' (T_STRING), expecting variable (T_VARIABLE) in /in/pT69l on line 6
Process exited with code 255.
Output for 5.3.0 - 5.3.28
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE in /in/pT69l on line 6
Process exited with code 255.

preferences:
186.1 ms | 1395 KiB | 61 Q