simon-forb / php-formula-interpreter
PHP公式解释器
v1.0.4
2022-04-04 06:32 UTC
Requires
- php: ^8.1|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^v2
- phing/phing: ~2.16.1
- phpunit/phpunit: ^9
- symfony/class-loader: 2.1.*
This package is auto-updated.
Last update: 2024-09-04 11:42:36 UTC
README
PHP公式解释器
为什么使用这个库?
有些用户可能想要执行简单的计算,并且尽可能多地改变它。在使用库之前,你可以使用 eval
函数。但这种方法有两个主要缺点
-
安全性。PHP脚本会被eval函数评估。PHP是一种非常强大的语言,可能对于用户来说过于强大,尤其是当用户想要注入恶意代码时。
-
复杂性。PHP对于不懂编程语言的人来说也很复杂。解析类似Excel的公式可能更好。
安装
使用Composer安装它
composer require simon-forb/php-formula-interpreter
它是如何工作的?
首先,创建一个FormulaInterpreter\Compiler
实例
$compiler = new FormulaInterpreter\Compiler();
然后使用compile()
方法解析您想要解释的公式。它将返回一个FormulaInterpreter\Executable
实例
$executable = $compiler->compile('2 + 2');
最后,从可执行文件中运行公式
$result = $executable->run(); // $result equals 4
使用运算符
乘法(*)和除法(/)运算符先被评估,然后是加法(+)和减法(-)
您也可以使用括号来强制表达式的优先级,如下所示
'2 * (3 + 2)'
您可以使用任意数量的括号。
'2 * (2 * (3 + 2 * (3 + 2)) + 2)'
比较运算符
支持的比较运算符有=
、!=
、<>
、>=
、>
、<=
、'<
'。
'1 = 1' //true '1 != 1' //false '1 != 2' //true '1 < 2' //true
布尔运算符
支持的布尔运算符有AND
和OR
。
'(4 > 0) AND (3 > 2)' //true '(4 > 0) AND (3 < 2)' //false '(4 > 0) OR (3 < 2)' //true '(4 < 0) AND (3 < 2)' //false
未来运算符
将来将以函数的形式实现其他运算符,如取模、幂等。
使用变量
变量只是公式中的一个单词,如下所示
'price * rate / 100'
在执行公式之前,请确保将所有必需的变量注入到一个数组中
$variables = [
'price' => 40.2,
'rate' => 12.8
];
$executable->run($variables);
变量现在支持点.
作为名称。
$variables = [ 'user.name' => 'John Doe' 'user.age' => '23' ]; $executable->run($variables);
字符串支持
变量可以包含字符串。使用双引号("
)表示字符串。
'a = "Hello world"'
使用函数
以下是一个使用函数的表达式示例
'cos(0)'
可用函数:pi
、pow
、cos
、sin
、sqrt
和modulo
您可以使用任意数量的函数
'pow(sqrt(4), 2)'
自定义函数
现在您可以在编译前添加函数,如果您想添加更多变量。
$compiler = new Compiler(); $compiler->registerFunction('foobar', function ($a, $b) { return $a + $b; }); $executable = $compiler->compile("foobar(foo, bar)"); $params = [ 'foo' => 1, 'bar' => 2 ]; $executable->run($params);
列出参数
您可以通过运行run()
方法来获取必须提供给可执行文件的所有变量的列表
$executable = $compiler->compile('foo + bar'); print_r($executable->getParameters());
这将输出
Array ( [0] => foo [0] => bar )