/
OperatorStack.php
92 lines (79 loc) · 1.68 KB
/
OperatorStack.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
require_once "Stack.php";
/**
* An extension of Stack specifically for arithmetical operators, represented by Operator.
*/
class OperatorStack extends Stack{
function push($operator){
$op = new Operator($operator);
parent::push($op);
}
function dump(){
$ret = "<table>";
for($i = count($this->stack) - 1 ; $i >= 0 ; $i--){
$ret .= "<tr><td>" . $this->stack[$i]->get_operator() . "</td><td>" . $this->stack[$i]->get_precedence() . "</td></tr>";
}
$ret .= "</table>";
return $ret;
}
}
/**
* An object that represents a single operator.
*/
class Operator{
private $operator;
private $precedence;
/**
* class instance constructor
* sets precedence based on input
*/
function __construct($operator){
$this->operator = $operator;
$prec = 0;
switch($operator){
case "EOI":
$prec = 0;
break;
case "(":
$prec = 1;
break;
case "+":
$prec = 2;
break;
case "-":
$prec = 2;
break;
case "*":
$prec = 3;
break;
case "/":
$prec = 3;
break;
default:
throw new InvalidOperatorException($operator);
break;
}
$this->precedence = $prec;
}
/**
* @return operator
*/
function get_operator(){
return $this->operator;
}
/**
* @return operator
*/
function get_precedence(){
return $this->precedence;
}
}
/**
* An exception thrown when an invalid text representation of an arithmetical operator is passed into Operator's constructor.
*/
class InvalidOperatorException extends Exception {
function __construct($operator){
parent::__construct("Invalid operator: " . $operator);
}
}
?>