Download the PHP package khumbal/php-formula-interpreter without Composer
On this page you can find all versions of the php package khumbal/php-formula-interpreter. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-formula-interpreter
php-formula-interpreter
A formula interpreter for php
Why this library ?
Some user could wants to perform a simple calculation and being able to change it as much as he can. Before using a library, you could use the eval
function. But this method has two major drawbacks :
-
Security. A php script is being evaluated by the eval function. Php is a very powerful language, perhaps too powerful for a user especially when the user wants to inject malicious code.
- Complexity. Php is also complex for someone who doesn't understand programming language. It could be nice to interpret an excel-like formula instead.
Installing
Use Composer to install it:
How does it work ?
First, create an instance of FormulaInterpreter\Compiler
Then use the compile()
method to parse the formula you want to interpret. It will return an instance of FormulaInterpreter\Executable
:
Finally run the formula from the executable :
Using operators
Operator multiplication (*) and division () are being evaluted first, then addition (+) and subtraction (-)
You can also force the prioriry of an expression by using parentheses like this
You can use as many parentheses as you like.
Comparison operators
Supported comparison operators are =
, !=
, <>
, >=
, >
, <=
, '<'.
Boolean operators
Supported boolean operators are AND
and OR
.
Future operators
Others operators like modulo, power, etc. will be implemented in the future as functions.
Using variables
A variable is just a word inside your formula like this :
Just before executing a formula, make sure to inject all the required variables in an array
Variables now supports dot .
as the name.
String support
Variables can contain string. Use double quote ("
) for denote a string.
Using functions
Here is an example of expression using a function :
Available functions : pi
, pow
, cos
, sin
, sqrt
& modulo
You can embed functions as much as you like
Custom functions
Now function can be added before compiling should you want to add more variables.
Listing parameters
You can get a list of all variables that must be provided to the run()
method in order to run the executable:
This will output: