This method has two major drawbacks:
I created this, check it out: Formula Interpreter
How does it work ?
First, create an instance of FormulaInterpreter
with the formula and its parameters
$formulaInterpreter = new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]);
Use the execute()
method to interpret the formula. It will return the result:
echo $formulaInterpreter->execute();
in a single line
echo (new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]))->execute();
Examples
# Formula: speed = distance / time
$speed = (new FormulaInterpreter("distance/time", ["distance" => 338, "time" => 5]))->execute() ;
echo $speed;
#Venezuela night overtime (ordinary_work_day in hours): (normal_salary * days_in_a_work_month)/ordinary_work_day
$parameters = ["normal_salary" => 21000, "days_in_a_work_month" => 30, "ordinary_work_day" => 8];
$venezuelaLOTTTArt118NightOvertime = (new FormulaInterpreter("(normal_salary/days_in_a_work_month)/ordinary_work_day", $parameters))->execute();
echo $venezuelaLOTTTArt118NightOvertime;
#cicle area
$cicleArea = (new FormulaInterpreter("3.1416*(radio*radio)", ["radio" => 10]))->execute();
echo $cicleArea;
About the formulas
- It must contain at least two operands and an operator.
- Operands' name could be in upper or lower case.
- By now, math functions as sin, cos, pow… are not included. I'm working to include them.
- If your formula is not valid, you will get an error message like: Error, your formula (single_variable) is not valid.
- Parameters' values must be numeric.
You can improve it if you want to!
eval()
, but no one should ever use eval for anything ever. Check this solution. – Priestly$ma
string coming from? User input? What if I sentrmdir('/var/www');
or something as my input? – Germangermanaeval()
code into a vulnerable web page. – Priestly