Jump to content

Evaluating math formulas


Alex_

Recommended Posts

Hey.

 

So imagine this example...

 

 

class FormulaEvaluator {
...... //Construct & variables here..
 
public function exec() {
//Missing some lines here, but you get the idea
$formula = $this->formula;
$context = (array) $this;
ob_start();
$res = eval('return ' . $formula . ';');
}
}
 
$formulaEvaluator = new FormulaEvaluator();
$formula = '10 * (($Test * 2) + ($Test2 / 3))';
$formulaEvaluator->formula = $formula;
$formulaEvaluator->Test = 20000;
$formulaEvaluator->Test2 = 300000;
$res = $formulaEvaluator->exec();
echo $res; //1400000

 

The code we have is working as intended, but we want to avoid using eval. I know it's a pretty common question, and the answer is usually the same, but is there any way to do something similar without using eval?

Link to comment
https://forums.phpfreaks.com/topic/292211-evaluating-math-formulas/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.