In PHP, creating a calculator requires parsing and evaluating mathematical expressions entered by a user. This can be challenging, as it involves handling user input and applying mathematical operations.
One recommended approach is to leverage the Shunting Yard Algorithm. This algorithm converts mathematical expressions into Reverse Polish Notation (RPN), which is easier to evaluate.
Here's a simplified example using the Shunting Yard Algorithm:
// Terminal expression abstract class abstract class TerminalExpression { public function operate() { return $this->value; } public function isOperator() { return false; } public function isParenthesis() { return false; } public function isNoOp() { return false; } } // Operator expression abstract class abstract class Operator extends TerminalExpression { public function isOperator() { return true; } } // Stack implementation class Stack { private $data = []; public function push($element) { $this->data[] = $element; } public function peek() { return end($this->data); } public function pop() { return array_pop($this->data); } } // Math class for evaluation class Math { public function evaluate($expression) { $stack = $this->parse($expression); return $this->run($stack); } private function parse($expression) { $tokens = $this->tokenize($expression); $output = new Stack(); $operators = new Stack(); foreach ($tokens as $token) { $type = TerminalExpression::factory($token); if ($type->isOperator()) { $this->parseOperator($type, $output, $operators); } elseif ($type->isParenthesis()) { $this->parseParenthesis($type, $output, $operators); } else { $output->push($type); } } while (($op = $operators->pop())) { if ($op->isParenthesis()) { throw new RuntimeException('Mismatched Parenthesis'); } $output->push($op); } return $output; } private function run(Stack $stack) { while (($operator = $stack->pop()) && $operator->isOperator()) { $value = $operator->operate($stack); if ($value !== null) { $stack->push(TerminalExpression::factory($value)); } } return $operator ? $operator->render() : $this->render($stack); } protected function tokenize($string) { return preg_split('((\d+|\+|-|\(|\)|\*|/)|\s+)', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); } } $math = new Math(); $answer = $math->evaluate('(2 + 3) * 4'); var_dump($answer); // int(20)
This example demonstrates how to use the Shunting Yard Algorithm to parse and evaluate a simple mathematical expression.
The above is the detailed content of How to Build a Calculator in PHP Using the Shunting Yard Algorithm?. For more information, please follow other related articles on the PHP Chinese website!