Exemple #1
0
            if ($token instanceof Number) {
                $tempStack->push($token);
            } elseif ($token instanceof Operator || $token instanceof Funct) {
                /** @var $token Operator|Funct */
                if ($tempStack->count() < $token->numOfArgs()) {
                    throw new Exception(sprintf('Required %d arguments, %d given.', $token->numOfArgs(), $tempStack->count()));
                }
                $arg = $tempStack->popMultiple($token->numOfArgs());
                $tempStack->push($token->execute(array_reverse($arg)));
            }
        }
        return $tempStack->pop()->value;
    }
    public function evaluate()
    {
        $this->convertToRpn();
        return $this->process();
    }
}
/**
 * sin(PI/2+2*PI)+cos(2*2*PI)+tg(2*PI)+ctg(PI/2+2*PI)+2^2/2-2+2*2-4 + ((2+2)*2-(4/2*2)*2) =
 * 1 + 1 + 0 + 0 + 0
*/
$ret = null;
try {
    $calc = new Calc($_GET['expression']);
    $ret = $calc->evaluate();
} catch (Exception $e) {
    $ret = $e->getMessage();
}
echo json_encode(array('result' => $ret));