How to make a calculator in PHP?

后端 未结 3 910
暖寄归人
暖寄归人 2020-11-22 13:43

I want to use PHP to calculate simple algebraic expressions like, 8*(5+1), entered via an tag by a normal user (which means,

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 13:50

    There is a Math Parser class called bcParserPHP that might be of interest.

    Seems fairly simple to use and pretty powerful.

    Example code from their site:

    $parser = new MathParser();
    $parser->setVariable('X', 5);
    $parser->setVariable('Y', 2);
    $parser->setExpression('COS(X)+SIN(Y)/2');
    echo $parser->getValue();
    

    Unfortunately, it's a commercial product; I don't know if that would stop you using it or not (guess it depends on the price and on your needs).

    A non-commercial alternative might be this one: http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html

    Note that this class uses eval() internally, which I would avoid doing if possible.

    Failing that, writing your own language parser would be the ideal solution, but not really sensible to do that in PHP.

提交回复
热议问题