mormat / php-formula-interpreter
PHP 公式解释器
Requires (Dev)
- symfony/class-loader: 2.1.*
This package is not auto-updated.
Last update: 2024-09-18 16:53:21 UTC
README
一个独立的 PHP 库,用于解析和运行公式
通过 composer 安装
composer require mormat/php-formula-interpreter
它是如何工作的?
首先,创建一个 \Mormat\FormulaInterpreter\Compiler
实例
$compiler = new \Mormat\FormulaInterpreter\Compiler();
然后使用 compile()
方法解析您想要解释的公式。它将返回一个 \Mormat\FormulaInterpreter\Executable
实例
$executable = $compiler->compile('2 + 2');
最后,从可执行文件中运行公式
$result = $executable->run(); // $result equals 4
公式的示例
// variables can be used
price + 2
// parenthesis can be used
(1 + 2) * 3
// default functions are available
sqrt(4)
// complex formulas can be used
(((100 * 0.43075) * 1.1 * 1.5) / (1-0.425)) * 1.105
// string are supported
lowercase('FOO')
// arrays are supported
count([2, 3, 4])
// custom functions can be registered
your_function_here(2)
// use the in operator to check if an item is in array
1 in [1, 2, 3] // returns true
// use the in operator to check if a substring is in a string
'Wars' in 'Star Wars'
公式中支持的数据类型
数值类型
数值可以是整数或浮点数
2 // integer
2.30 // float
字符串类型
使用简单引号作为字符串的分隔符
'foobar'
数组类型
使用逗号分隔数组项,使用括号包裹数组项
[1, 2, 3]
函数、字符串和操作可以作为数组项使用
[cos(0), 'foobar', 2 + 2]
使用运算符
以下运算符可用
运算符 *
和 /
首先被评估,然后是运算符 +
和 -
您也可以通过使用括号来强制表达式的优先级,如下所示
2 * (3 + 2)
您可以使用任意数量的括号
2 * (2 * (3 + 2 * (3 + 2)) + 2)
使用变量
变量只是公式中的一个词,如下所示
price * rate / 100
在 PHP 中执行公式之前,请确保将所有所需的变量注入到数组中
$variables = array( 'price' => 40.2, 'rate' => 12.8 ); $executable->run($variables);
使用函数
可用函数
如何注册自定义函数?
在 \Mormat\FormulaInterpreter\Compiler
类中使用 registerCustomFunction()
方法。
自定义函数必须实现 \Mormat\FormulaInterpreter\Functions\FunctionInterface
接口。此接口包含以下方法
- getName() 返回函数的名称
- supports($arguments) 如果发送给函数的 $arguments 有效,则返回 true。
- execute($arguments) 执行函数并返回值。
为什么使用这个库?
一些用户可能想要执行简单的计算,并且能够尽可能多地更改它。在使用库之前,您可以使用 eval
函数。但是,这种方法有两个主要缺点
-
安全性。PHP 脚本由 eval 函数执行。PHP 是一种非常强大的语言,可能对用户来说过于强大,尤其是当用户想要注入恶意代码时。
-
复杂性。PHP 对不熟悉编程语言的人来说也很复杂。解释类似于 Excel 的公式可能更好。