Class: MathParser
Source Location: /mathparser/mathparser.php
MathParser is a mathematical expression parser class for PHP. MathParser parses and evaluates mathematical formulas given as strings at runtime. Math expressions can contain variables, functions, numeric literals combined with basic mathematical operators +, -, /, *, ^, % (modulus).
|
|
|
Class Details
[line 135]
MathParser is a mathematical expression parser class for PHP. MathParser parses and evaluates mathematical formulas given as strings at runtime. Math expressions can contain variables, functions, numeric literals combined with basic mathematical operators +, -, /, *, ^, % (modulus). MathParser can utilize user defined variables, user defined functions that are implemented in PHP language.
Math parser library features at a glance include:
Easy to use, simple class API. Functions with 0 or more number of parameters in the form of: f(x,y,z, ...) Functions with unknown number of parameters, e.g. SUM(a,b,c,...) Comes with predefined functions. You can create custom functions/variables with callbacks to the functions that you define in your source code, either through delegates or interfaces. VariableResolver, a callback function to provide values for undefined variables. Function/variable names start with letters and can contain letters, numbers and underscore (_). Expression can contain string literals, variable values and function return values can be strings. Arithmetic Operators: +, -, /, *, ^, %(mod) Boolean Operators: <, >, =, &, |, ! ,<>, >=, <= String concatenation with & or + Optimization: Constant expression elimination for repeated tasks. Paranthesis: ( List of predefined functions is available in the documentation. Provides localization support which is a dictionary of message-keys to messages you can set. Royalty free distribution. Comes as source code.
You may ask why not use PHP eval() function? The answer is security. eval() is a security nightmare if you ask for formula input from the user. PHP syntax for formulas with $ signs is not intuitive either. The aim of MathParser is to be a a secure, simple math evaluator alternative to eval(). Please keep in mind, MathParser only evaluates mathematical expressions given using a simple syntax that consists of numbers, variables, function calls and paranthesis. MathParser does not evaluate PHP expressions.
Predefined functions are:
SQR: Square function which can be used as SQR(X)
SIN: Sinus function which can be used as SIN(X), X is a real-type expression. Sin returns the sine of the angle X in radians.
COS: Cosinus function which can be used as COS(X), X is a real-type expression. COS returns the cosine of the angle X in radians.
ATAN: ArcTangent function which can be used as ATAN(X) Returns the arctangent of a number as a numeric value between -PI/2 and PI/2 radians.
SINH: Sinus Hyperbolic function which can be used as SINH(X)
COSH: Cosinus Hyperbolic function which can be used as COSH(X)
COTAN: which can be used as COTAN(X)
TAN: which can be used as TAN(X)
EXP: which can be used as EXP(X)
LN: natural log, which can be used as LN(X)
LOG: 10 based log, which can be used as LOG(X)
SQRT: which can be used as SQRT(X)
ABS: absolute value, which can be used as ABS(X)
SIGN: SIGN(X) returns -1 if X<0; +1 if X>0, 0 if X=0; it can be used as SQR(X)
TRUNC: Discards the fractional part of a number. e.g. TRUNC(-3.2) is -3, TRUNC(3.2) is 3.
CEIL: CEIL(-3.2) = 3, CEIL(3.2) = 4
FLOOR: FLOOR(-3.2) = -4, FLOOR(3.2) = 3
VAL: VAL("3.1") = 3.1 Returns the floating point numeric value of the string argument.
Predefined functions that take two parameters are:
POW: The Power function raises Base to any power. For fractional exponents or exponents greater than MaxInt, Base must be greater than 0.
LOGN: The LogN function returns the log base N of X. Example: LOGN(10, 100) = 2
MIN: MIN(2, 3) is 2.
MAX: MAX(2, 3) is 3.
IF: The IF(b, case1, case2) function provides branching capability. If b is not 0, then it returns case1, else it returns case2. Behavior is similar to PHP's: return b ? case1 : case2; If b==0 then case1 will not be Evaluated, and vice versa. Example: IF(HEIGHT, 3/HEIGHT, 3) will make sure 3/HEIGHT does not cause division by zero.
Predefined functions that take no parameters are: RND: RND() function generates a random number (double value) between 0 and 1.
STR: STR(123) function returns the string representation of the passed value: "123".
SUBSTR: SUBSTR("Hello", 1,3) function returns the substring just like PHP substr function. The first parameter is the string, the second parameter is which index (0 based) to start copying, and the last parameter is the number of characters to copy. For example, SUBSTR("Hello", 1,3) returns "ell".
STRLEN: STRLEN("abc") function returns the length of the string parameter. For example, for "abc" it returns 3.
CONCAT: CONCAT("abc","def",...) function returns the concatanated strings: "abcdef". There is no preset limit on the number of parameters.
TRIM: TRIM(" abc ") function returns the trimmed version of the string parameter: " abc " -> "abc".
SUM: SUM(2,3,5,...) functions returns the sum of it's arguments. There is no preset limit on the number of parameters.
Class Variables
Class Methods
constructor __construct [line 392]
MathParser __construct(
)
|
|
Constructor for the MathParser.
Tags:
method createDefaultFuncs [line 877]
void createDefaultFuncs(
)
|
|
CreateDefaultFuncs method creates some predefined functions in the parser's list of functions.
Predefined functions are:
SQR: Square function which can be used as SQR(X)
SIN: Sinus function which can be used as SIN(X), X is a real-type expression. Sin returns the sine of the angle X in radians.
COS: Cosinus function which can be used as COS(X), X is a real-type expression. COS returns the cosine of the angle X in radians.
ATAN: ArcTangent function which can be used as ATAN(X) Returns the arctangent of a number as a numeric value between -PI/2 and PI/2 radians.
SINH: Sinus Hyperbolic function which can be used as SINH(X)
COSH: Cosinus Hyperbolic function which can be used as COSH(X)
COTAN: which can be used as COTAN(X)
TAN: which can be used as TAN(X)
EXP: which can be used as EXP(X)
LN: natural log, which can be used as LN(X)
LOG: 10 based log, which can be used as LOG(X)
SQRT: which can be used as SQRT(X)
ABS: absolute value, which can be used as ABS(X)
SIGN: SIGN(X) returns -1 if X<0; +1 if X>0, 0 if X=0; it can be used as SQR(X)
TRUNC: Discards the fractional part of a number. e.g. TRUNC(-3.2) is -3, TRUNC(3.2) is 3.
CEIL: CEIL(-3.2) = 3, CEIL(3.2) = 4
FLOOR: FLOOR(-3.2) = -4, FLOOR(3.2) = 3
VAL: VAL("3.1") = 3.1 Returns the floating point numeric value of the string argument.
Predefined functions that take two parameters are:
POW: The Power function raises Base to any power. For fractional exponents or exponents greater than MaxInt, Base must be greater than 0.
LOGN: The LogN function returns the log base N of X. Example: LOGN(10, 100) = 2
MIN: MIN(2, 3) is 2.
MAX: MAX(2, 3) is 3.
IF: The IF(b, case1, case2) function provides branching capability. If b is not 0, then it returns case1, else it returns case2. Behavior is similar to PHP's: return b ? case1 : case2; If b==0 then case1 will not be Evaluated, and vice versa. Example: IF(HEIGHT, 3/HEIGHT, 3) will make sure 3/HEIGHT does not cause division by zero.
Predefined functions that take no parameters are: RND: RND() function generates a random number (double value) between 0 and 1.
STR: STR(123) function returns the string representation of the passed value: "123".
SUBSTR: SUBSTR("Hello", 1,3) function returns the substring just like PHP substring function. The first parameter is the string, the second parameter is which index (0 based) to start copying, and the last parameter is the number of characters to copy. For example, SUBSTR("Hello", 1,3) returns "ell".
STRLEN: STRLEN("abc") function returns the length of the string parameter. For example, for "abc" it returns 3.
CONCAT: CONCAT("abc","def",...) function returns the concatanated strings: "abcdef". There is no preset limit on the number of parameters.
TRIM: TRIM(" abc ") function returns the trimmed version of the string parameter: " abc " -> "abc".
SUM: SUM(2,3,5,...) functions returns the sum of it's arguments. There is no preset limit on the number of parameters.
User functions can be added using CreateFunc method. Functions and Variables can be deleted using DeleteVar, DeleteFunc, DeleteAllVars, DeleteAllFuncs methods.
Tags:
method createDefaultVars [line 925]
void createDefaultVars(
)
|
|
X, Y and PI variables can be predefined and can be immediately used in the expression. Initial values of X and Y are 0. PI is 3.14159265358979
Tags:
method createFunc [line 766]
void createFunc(
string
$newFuncName, string
$funcAddr, int
$paramCount)
|
|
CreateFunc method creates a new function that takes n number of parameters (could be 0) in the parser's list of functions. If the function name already exists then this method throws Exception. Function name is not case sensitive.
The second parameter is the name of the user defined function that is globally available:
function funcName($parameter1 [, $parameter2,...]);
During evaluation of the expression, when the registered function name is encountered, the user supplied funcName will be called and variables will be passed.
This user defined function will need to return a result (representing the value of the function) based on the parameters passed as an array of double values. If the number of parameters that a function takes is not known ahead of time, then the $paramCount parameter should be -1. Otherwise, it will be the number of parameters that will be passed to the function at runtime. Knowing the number of parameters ahead of time helps detect syntax errors during parsing. For example, if SIN(x) function descriptor did not tell us that it was taking only 1 parameter, then an expression like: SIN(x,y) would not cause syntax error during parsing, and if the implementation of SIN(x) did not check actual runtime number of parameters passed, then the problem could go undetected and the second y parameter could be ignored silently.
Tags:
Parameters:
method createVar [line 734]
void createVar(
string
$varName, mixed
$varValue, [string
$valueProvider = null])
|
|
Creates a variable with given name and initial value. If the variable already exists, sets it's value to the specified value. Throws Exception if $varName is not a valid variable name.
Tags:
Parameters:
method createVarNode [line 2185]
object createVarNode(
string
$varName)
|
|
This method can be overridden to return a Node that is fancy enough to lookup values from a database etc to come up with variable values at evaluation time.
Tags:
Parameters:
method deleteAllFuncs [line 1007]
DeleteAllFuncs method deletes all variables from the list of available functions.
This action may be useful when number of unused functions is too high that causes performance to degrade.
When a function is deleted Dirty flag is set to true so that next time the Evaluate function is called the expression will be reparsed.
Tags:
method deleteAllVars [line 992]
DeleteAllVars method deletes all variables from the list of available variables.
This action may be useful when number of unused variables is too high that causes performance to degrade.
When a variable is deleted Dirty flag is set to true so that next time the Evaluate function is called the expression will be reparsed.
Tags:
method deleteFunc [line 971]
void deleteFunc(
string
$funcName)
|
|
DeleteFunc method deletes an existing function from the list of available functions. If the function does not exist, deleteFunc does nothing.
When a function is deleted Dirty flag is set to true so that next time the Evaluate function is called the expression will be reparsed. Function name is not case sensitive.
Tags:
Parameters:
method deleteVar [line 948]
void deleteVar(
string
$varName)
|
|
DeleteVar method deletes an existing variable from the list of available variables. If the variable does not exist, then DeleteVar does nothing.
When a variable is deleted Dirty flag is set to true so that next time the Evaluate function is called the expression will be reparsed. Variable name is not case sensitive.
Tags:
Parameters:
method evaluate [line 602]
Evaluates the expression and returns the result of it. If it cannot be parsed or evaluated then this method throws Exception.
Calling this method is identical to calling getValue()
Tags:
method freeParseTree [line 1018]
FreeParseTree can be explicitly called to free the resources taken by the allocated Parse tree when an expression is parsed. FreeParseTree sets the Dirty flag to true so that next time the Evaluate function is called, expression will be parsed forming a new, valid parse tree to be evaluated.
Tags:
method getExpression [line 2138]
Expression property represents the mathematical expression which is input to be Evaluated by the user. The expression can contain variables such as X, Y, T, HEIGHT, WEIGHT and so on. The values of these constants are set before the expression is evaluated. The values of the variables can be set before the expression is evaluated or the values can be provided during evaluation using a PHP function registered as $VariableResolver.
Tags:
method getFunctions [line 1153]
Returns a String array of function names declared for this parser. Elements of the array are guaranteed not to be null. Returns array of function names that are currently defined for this parser instance.
Tags:
method getStrConcatOperator [line 330]
boolean getStrConcatOperator(
)
|
|
If you setStringLiteralsAllowed to true, MathParser allows string literals and variables to be used in the expression. By default string values can be concatenated to each other using plus (+) operator. StrConcatOperator property allows the user to set ampersand instead (&). You can only set plus(+) or ampersand (&)
Tags:
method getStringLiteralsAllowed [line 297]
boolean getStringLiteralsAllowed(
)
|
|
Can the expression contain string literals such as "abc", "hello world" etc. If you do not want to support strings in the expression, (want numeric processing only), then you can set this property to false and then you can also remove string functions from the list of available functions. Then the parser will solely work on numeric expressions. The string literals may also be useful in numeric context where the string can refer to a database table or column name and can be passed to functions that actually use these strings to lookup these values in databases to return numeric values too.
Tags:
method getTranslationStrings [line 445]
array &getTranslationStrings(
)
|
|
Returns the existing trasnlatable strings used to report error messages. To use this component in a localized application, set the translated versions of strings for each value that exists in the hashtable. By default, same hashtable is shared between all instances of the parser. To change translation strings, set a new hashtable of your own for the parser instance instead of editing the values contained in this hashtable if you do not wish other parser instances not to be effected. Returns dictionary (array) of key/value pairs where value is a Locale dependent, typically translated String, that may contain placeholder parameters using %s.
Tags:
method getValue [line 1182]
Value property is a read only property which returns the result of the expression. throws Exception if expression cannot be parsed. Return value is either Double or String.
Tags:
method getValueAsDouble [line 1192]
float getValueAsDouble(
)
|
|
Value property is a read only property which returns the result of the expression. throws Exception if expression cannot be parsed. Return value is is a Double.
Tags:
method getValueAsString [line 1207]
string getValueAsString(
)
|
|
Value property is a read only property which returns the result of the expression. throws Exception if expression cannot be parsed. Return value is a string.
Tags:
method getVariable [line 531]
Returns getVariable(
string
$varName)
|
|
Variable property is a way to set and get variable values. Throws Exception if the variable does not exist. Variable name is not case sensitive.
Tags:
Parameters:
method getVariableResolver [line 374]
string getVariableResolver(
)
|
|
VariableResolver is used as a callback function that returns the values of variables when asked. This is useful when a variable cannot be defined before the parse operation. If VariableResolver property is set, it will be used to resolve variables that were not defined at the time parse operation has started. This means that syntax errors regarding undefined variables will not be caught at parse time. This VariableResolver (user implementation) will decide whether a variable name is valid or not. This is useful when for example the value comes from a database lookup. In some cases, the problem domain is too big to define the variables ahead of time. In such cases, it makes sense to parse with the assumption that it is a valid variable and resolve it's value when needed on demand during evaluation.
Tags:
method getVariables [line 1142]
Returns the list of variables as an array of Strings. Each element of the array is guaranteed not to be null. Returns array of variable names that are currently defined for this parser instance.
Tags:
method getVariablesUsed [line 1098]
array getVariablesUsed(
)
|
|
Returns the list of variables used in the current expression as an array of Strings. Each element of the array is guaranteed not to be null. If variables are not defined ahead of time, then $VariableResolver must have been set. Otherwise, when an undefined variable is found in the expression, ParserException will be thrown. Return array of variable names that are currently defined for this parser instance.
Tags:
method isFunction [line 1083]
boolean isFunction(
string
$funcName)
|
|
Returns true if a function with the name 'funcName' is present in any of the current functions lists. Returns true if a function with the given name is defined. False otherwise.
Tags:
Parameters:
method isFunctionUsed [line 1051]
boolean isFunctionUsed(
string
$funcName)
|
|
Returns true if a function with the name 'funcName' is used in the current expression. Function name is not case sensitive. Throws exception if expression is not parsed and cannot be parsed. Returns true if the function with the given name was actually used in the current expression. Returns false otherwise.
Tags:
Parameters:
method isOptimizationOn [line 2165]
boolean isOptimizationOn(
)
|
|
Set OptimizationOn to let the bcParser component evaluate constant expressions at parse time. The optimized parse tree will enhance subsequant evaluation operations, though initial parsing will be slower.
Optimization is good if you are going to parse once and evaluate the same expression many many times with different variable values.
Tags:
method isVariable [line 1070]
boolean isVariable(
string
$varName)
|
|
Returns true if a variable with the name 'varName' is present in the current variables list. For backward compatibility, IsVariable returns true for constants also. For constants, you can use IsConstant. Returns true if the variable exists in the list of variables of the parser instance. false otherwise.
Tags:
Parameters:
method isVariableUsed [line 1031]
Returns isVariableUsed(
string
$varName)
|
|
Returns true if a variable with the name 'varName' is used in the current expression. Variable name is not case sensitive. Throws exception if expression is not parsed and cannot be parsed.
Tags:
Parameters:
method parse [line 624]
Parses the expression and forms a parse tree. Throws Exception if it cannot parse. Upon successful completion of parsing, it will set the Dirty flag to false, so that unless the expression is changed or variables and functions added or removed, expression does not need to be re-parsed. Users may want to call the parse method directly to check the validity of an input expression using a try-except block.
If OptimizationOn property is true, Parse method will optimize the parse tree by evaluating constant branches of the parse tree at that moment, so that Evaluate function will run faster.
Tags:
method setExpression [line 2147]
void setExpression(
string
$value)
|
|
Tags:
Parameters:
method setOptimizationOn [line 2174]
void setOptimizationOn(
boolean
$value)
|
|
Tags:
Parameters:
method setStrConcatOperator [line 338]
void setStrConcatOperator(
string
$value)
|
|
Tags:
Parameters:
method setStringLiteralsAllowed [line 306]
void setStringLiteralsAllowed(
$value
$value)
|
|
Tags:
Parameters:
method setTranslationStrings [line 519]
void setTranslationStrings(
array
$strings)
|
|
Sets the key/value pairs where value is a translated message string for the parser to use while constructing messages. This mechanism allows the parser instances in the same VM efficiently use different locales independent of each other. not for each instance of the parser.
Messages may contain parameter placeholders. For example: "Variable %s does not exist". You need to have your own messages translated accordingly.
Tags:
Parameters:
method setVariable [line 562]
void setVariable(
string
$varName, mixed
$newVal, [string
$fn_valueProvider = null])
|
|
Variable property is a way to set and get variable values. setVariable function creates the variable if the variable does not exist. Variable name is not case sensitive. Throws exception if the variable needs to be created and the name is not a valid variable name. CreateVar is just an alias for this method.
Tags:
Parameters:
method setVariableResolver [line 382]
void setVariableResolver(
string
$value)
|
|
Tags:
Parameters:
|
|
|