title: php calculator class
body: <p>I am stuck in resolving a PHP script.</p>
  
  <p>I want to calculate a result from a set of instructions. Instructions comprise of a keyword and a number that are separated by a space per line. Instructions are loaded from file and results are output to the screen. Any number of Instructions can be specified. Instructions are operators (add, divide, subtract, multiply). The instructions will ignore mathematical precedence. The last instruction should be “apply” and a number (e.g., “apply 3”). The calculator is then initialised with that number and the previous instructions are applied to that number.</p>
  
  <pre><code>[Input]
  add 2
  multiply 3
  apply 3
  [Output]
  15
  </code></pre>
  
  <p>this is what i have tried but i cant get the logic to complete the methods</p>
  
  <pre><code>class Calculator {
      public $result = 0;
      public $queue = Array();
      public parseString($text) {
         // parse input string
         $cmds = explode(" ", $text);
         foreach($cmds as $cmd) {
            $cmd = trim($cmd);
            if(!$cmd) continue; // blank or space, ignoring
            $this-&gt;queue[] = $cmd;
         }
  
         // lets process commands
         $command = false;
         foreach($this-&gt;queue as $index =&gt; $cmd) { 
             if(is_number($cmd)) {
                 // if it's number fire previous command if exists
                 if(!$command || !method_exists($this, $command)) {
                     throw new Exception("Unknown command $command");
                 }
                 $this-&gt;$command($index, $cmd);
             }else{
                 $command = $cmd;
             }
         }
      }
      public function apply($index, $number) {
         // manipulate $result, $queue, $number
      }
      public function add($index, $number) {
         // manipulate $result, $queue, $number
      }
      public function substract($index, $number) {
         // manipulate $result, $queue, $number
      }
  }
  
  $calculator = new Calculator();
  $calculator-&gt;parseString('...');
  </code></pre>
  
  <p>how can i call or switch the add,divide,multiply,substract and how to distinguish and trigger apply word</p>
  
  <p>any kind of help will be appreciated.</p>