且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在php中使用字符串作为数学计算公式?

更新时间:2023-01-10 18:50:37

很遗憾,您需要对其进行评估.

Unfortunately, you need to eval it.

如果值是这样的:

$deviceData["devicename"] = [
    'a' => 20,
    'b' => 30,
    'c' => 580
];

您可能想要隔离它们,因为如果有超过 3 个等,您需要 extract() 来使用它们,封装在函数/闭包中会起作用.

You might want to isolate them as you will need to extract() them out to make use if there is more then 3 etc, encapsulating in function/closure would work.

<?php
$formula = '(($a+$b)/$c)';

$deviceData["devicename"] = ['a' => 20, 'b' => 30, 'c' => 580];

$runFormula = function ($formula, $data) { 
    extract($data); 
    return eval('return '.$formula.';'); 
};

echo $runFormula($formula, $deviceData["devicename"]);

https://3v4l.org/I2rbk

或者只是:

extract($deviceData["devicename"]); 
echo eval('return '.$formula.';'); 

但是您正在使用提取的内容污染全局变量表,可能会导致更多问题.

But you're polluting your global variable table with whats extracted, potentially causing more issues.

虽然如果公式是由用户定义的,请不要使用 eval,否则您会遇到安全问题.

Though dont use eval if the formula is defined by the user, or your will have security issues.

在任何情况下,我均不对任何损害承担任何责任,包括,但限于直接、间接、特殊或后果性损害因使用本产品而产生、由此产生或以任何方式与之相关提供的代码,无论是否基于保证、合同、侵权行为或除此以外;伤害是否是由人员或财产造成的或以其他方式;以及损失是否来自或产生的,结果,使用如果此代码.;p

In no respect shall I incur any liability for any damages, including, but limited to, direct, indirect, special, or consequential damages arising out of, resulting from, or any way connected to the use of the code provided, whether or not based upon warranty, contract, tort, or otherwise; whether or not injury was sustained by persons or property or otherwise; and whether or not loss was sustained from, or arose out of, the results of, the use if this code. ;p