如何避免对需要执行的特定变量字符串使用 eval

发布于 2024-10-06 18:37:40 字数 413 浏览 0 评论 0 原文

我使用 eval() 进行类似的操作:

$result = eval("return ".$value1.$operator.$value2.";");

其中运算符来自变量或数据库字段。

在不使用 eval 的情况下,我如何才能获得相同的结果?是否可以?

这不是安全问题,因为值/运算符不是用户输入的,但如果 这条注释 是可以参考的。另外,如果在某个时候我想尝试 Facebook 的 HipHop,我需要用其他东西替换 eval 的所有使用。

I have things like this using eval():

$result = eval("return ".$value1.$operator.$value2.";");

Where the operator is from a variable, or a db field.

How would I go about achieving the same result without using eval? Is it possible?

It's not a security concern as the values/operator aren't user entered, but it may be a performance concern if this comment at the PHP manual is anything to go by. Plus, if at some point I want to try out Facebook's HipHop I need to replace all uses of eval with something else.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

追星践月 2024-10-13 18:37:40
if(strcmp($operator, "+") == 0) {  
  return   $value1 + $value2;
}  
else if(strcmp($operator, "*") == 0) {  
return   $value1 * $value2;  
}  
...  

正如@Gumbo 提到的,您还可以使用 switch()

if(strcmp($operator, "+") == 0) {  
  return   $value1 + $value2;
}  
else if(strcmp($operator, "*") == 0) {  
return   $value1 * $value2;  
}  
...  

As @Gumbo mentioned, you can also use switch()

无风消散 2024-10-13 18:37:40

好吧,我不确定运算符,但您可以使用函数名称执行类似的操作:

function add($x, $y) {
    return $x + $y;
}

$value1 = 1;
$value2 = 2;
$func = "add";

$result = $func($value1, $value2);

您甚至可以使用内置函数执行此操作:

$func = 'array_sum';
$result = $func(array($value1, $value2));

Well, I'm not sure about operators, but you can do something like this with function names:

function add($x, $y) {
    return $x + $y;
}

$value1 = 1;
$value2 = 2;
$func = "add";

$result = $func($value1, $value2);

You can even do this with builtin functions:

$func = 'array_sum';
$result = $func(array($value1, $value2));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文