2016-07-28 114 views
3

我有3个变量和一个可信用户需要通过CMS定义的公式。这个公式将随时间变化,变量的值来自数据库。使用变量进行PHP计算

我该如何计算出答案?我认为EVAL是相关的,但不能完全得到它的工作

$width = 10; 
$height = 10; 
$depth = 10; 

$volumetric = '(W*H*D)/6000'; 

$volumetric = str_replace('W', $width, $volumetric); 
$volumetric = str_replace('H', $height, $volumetric); 
$volumetric = str_replace('D', $depth, $volumetric); 

eval($volumetric); 

这给了我:

Parse error: parse error in /path/to/vol.php(13) : eval()'d code on line 1 
+1

为什么你只写$ volumetric =($ width * $ height * $ depth)/ 6000。让它成为一个函数,并随时随地调用它。所以如果它会改变,你只会改变一个功能。 –

+0

将无法​​正常工作。非技术用户将需要通过CMS更新公式,所以我需要能够使用我从数据库中提取的变量($ width,$ height,$ depth),并将其应用于当前的公式 – Chris

+1

您需要非常在接受用户输入并使用'eval'时要小心,你必须清除输入内容,否则你会被打开以致被黑客入侵。 – Styphon

回答

1

您需要非常小心eval,因为您可以让用户直接在服务器上访问运行​​命令。请务必彻底了解并了解风险。

也就是说,你需要将结果赋值给一个变量。你也可以收拾你正在做的事情,你只需要一个str_replace。试试这个:

$width = 10; 
$height = 10; 
$depth = 10; 

$volumetric = '(W*H*D)/6000'; 
$volumetric = str_replace(['W', 'H', 'D'], [$width, $height, $depth], $volumetric); 

eval("\$result = $volumetric;"); 
echo $result; 
0

评估和演示是正确的路要走......我正确的代码是:

$width = 60; 
$height = 60; 
$depth = 60; 

$volumetric = '(W*H*D)/6000'; 

$volumetric = str_replace('W', $width, $volumetric); 
$volumetric = str_replace('H', $height, $volumetric); 
$volumetric = str_replace('D', $depth, $volumetric); 

eval('$result = '.$volumetric.';'); 

echo $result; 
0

你的出发点是真实的。如果你不想使用或编码复杂的解析器,eval是最好的选择。但是,eval将给定的字符串转换为PHP代码。所以,基本上你想要的就是这个;

$width = 10; 
$height = 10; 
$depth = 10; 

$volumetric = '(W*H*D)/6000'; 

$volumetric = str_replace('W', $width, $volumetric); 
$volumetric = str_replace('H', $height, $volumetric); 
$volumetric = str_replace('D', $depth, $volumetric); 

(10*10*10)/600; 

因此它输出错误。你应该把这个等式分配给变量。正确的方法是;

eval('$result = ('.$volumetric.');'); 

eval("\$result = ({$volumetric});") 

另外我想补充一下。 小心!同时使用eval。