开发者

Formula calculation mechanism for web

开发者 https://www.devze.com 2023-01-15 09:34 出处:网络
There is a group of simple formulas for calculating some values. I need to implement this for the web interface (I make this in PHP).

There is a group of simple formulas for calculating some values. I need to implement this for the web interface (I make this in PHP).

To store formulas I am using simple format like this: "X1+X2+X3". When I need to make calculations, I call function preg_replace in the loop for replacing X1, X2 .. by real data (entered by user or saved earlier - it is not important) Then I开发者_如何转开发 use function eval('$calculation_result ='. $trans_formula .';') where $trans_formula stores text of the formula with substituted data.

This mechanism looks like a primitive and I have a feeling that I'm trying to re-invent the wheel. Perhaps there are some ready algorithms, techniques, methods to accomplish this? Not necessary PHP code. I’ll appreciate even simple algorithm description.


The first thought that hit me: eval is bad!

How I would approach this problem:
1. I would store the formalue in postfix (polish notation) 2. Then I'd write a simple program to evaluate the expression. Its fairly easy to write a postfix evaluator.

This approach will also allow you to check things like value data types and range contraints, if need be. Also eliminates the huge risk of eval.

Cheers!


EDIT in response to your comment to the question:

If your users will be entering their own expressions, you will want to convert them to postfix too. Check out infix to postfix conversion.


Take a look at the evalMath class on PHPClasses.


If the formulas are predeterminated, as I suppose reading your question, it is non useful (better, it is dangerous) use the eval to evaluate them.

Create simple function and call them passing the appropriate parameters (after input checking).

For example, your example will be:

<?php
  function sumOfThree($x1, $x2, $x3) {
    return $x1+$x2+$x3;
  }

// and you can call it as usual:
$calculation_result = sumOfThree($first, $second, $third);
?>

You will get a lot of plus in

  • speed: eval is very slow to execute (even for easy functions);
  • debugging: you can debug you function (and get correct error messages);
  • security: Eval is easily exploitable.
0

精彩评论

暂无评论...
验证码 换一张
取 消