How to evaluate formula passed as string in PHP?
In PHP, you can use the eval() function to evaluate a string as PHP code. However, this function is not recommended for security reasons, as it can allow malicious code to be executed. A safer alternative is to use the create_function() function, which creates a function from a string.
Here is an example of how you can use the create_function() function to evaluate a mathematical expression:
<?php $expression = '2 + 2'; $fn = create_function('', "return ($expression);"); $result = $fn(); echo $result; // Output: 4
This will output the value of the expression, which is 4.
Another option is to use a library that can safely evaluate mathematical expressions. One such library is the EvalMath class, which can be found at [this link](http://www.phpclasses.org/browse/package/2695.html).
Here is an example of how you can use the EvalMath class to evaluate a mathematical expression:
<?php include('evalmath.class.php'); $m = new EvalMath; $result = $m->evaluate('2 + 2'); echo $result; // Output: 4
This will also output the value of the expression, which is 4.
Which method you choose to use depends on your specific needs. If you need a simple and easy-to-use solution, then the create_function() function is a good option. However, if you need a more robust and secure solution, then the EvalMath class is a better choice.
The above is the detailed content of How to Safely Evaluate a Mathematical Formula Passed as a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!