Home >Backend Development >PHP Tutorial >How Can I Build a PHP Calculator Using the Shunting Yard Algorithm?
Problem:
You want to develop a PHP calculator that evaluates simple algebraic expressions inputted by users in standard notation, displaying the evaluation process. The challenge lies in efficiently calculating the expression's value.
Answer:
Consider utilizing the Shunting Yard Algorithm for its simplicity and efficiency in evaluating algebraic expressions.
Expression Definitions:
Create classes to represent different elements of the expression, such as parentheses, numbers, operators, and so on:
class Parenthesis extends TerminalExpression { ... } class Number extends TerminalExpression { ... } class Addition extends Operator { ... } class Subtraction extends Operator { ... } class Multiplication extends Operator { ... } class Division extends Operator { ... } class Power extends Operator { ... }
Stack Implementation:
class Stack { protected $data = array(); // ... Methods for pushing, popping, and peeking from the stack ... }
Executor Class:
The executor class parses the expression using the Shunting Yard algorithm and evaluates it:
class Math { // ... Fields and methods for parsing, running, and evaluating the expression ... }
Example:
Here's an example of how to use the calculator:
$math = new Math(); $answer = $math->evaluate('(2 + 3) * 4'); var_dump($answer); // int(20) $answer = $math->evaluate('1 + 2 * ((3 + 4) * 5 + 6)'); var_dump($answer); // int(83)
This example covers grouping and operator precedence. However, you can customize the implementation to suit your specific requirements.
The above is the detailed content of How Can I Build a PHP Calculator Using the Shunting Yard Algorithm?. For more information, please follow other related articles on the PHP Chinese website!