我有一个产品数据库。某些产品需要特殊计算才能计算运输成本。
目前,我正在将公式硬编码为PHP代码中的函数。但我想改为允许将公式输入并作为字符串存储在我的 MYSQL 数据库中。
例如:
$quantity=5;
$shipping_rate=100;
SELECT shipping_formula FROM products WHERE product_id='1'
// DO QUERY
$shipping_formula_string=if($quantity>4){$shipping_cost=$shipping_rate*1.5}else{$shipping_cost=$shipping_rate} return $shipping_cost
$shipping_cost=do_calculation($shipping_formula_string);
这可能吗?我不想每次添加新产品时都必须深入研究我的代码。
出于安全原因,您应该使用 symfony 表达式语言而不是 eval。 请参阅 http://symfony.com/doc/current/components/expression_language/index.html您将拥有的优势是:
你。。。
- 可以将其作为独立组件安装
- 可以将表达式存储在数据库中,或者在哪里
- 保存以使用它
- 。还有更多像测试等等
这里有一个来自文档的简单示例:
$data = array('life' => 10, 'universe' => 10, 'everything' => 22);
echo $language->evaluate(
'data["life"] + data["universe"] + data["everything"]',
array(
'data' => $data,
)
);
// Will output 42
是的,这是可能的,这就是eval()
函数的用途。在您的情况下,它将是:
function do_calculation($code){
return eval($code);
}
现在你错过了语句末尾的分号,并且该字符串周围没有引号 - 尝试更正这一点:
$shipping_formula_string="if($quantity>4){$shipping_cost=$shipping_rate*1.5;}else{$shipping_cost=$shipping_rate;} return $shipping_cost;";
但事实是,这不是安全的解决方案。您最好将该代码存储在静态类中,并在需要时使用自动加载函数调用它们。