什么时候在php中是邪恶的? [英] When is eval evil in php?

查看:73
本文介绍了什么时候在php中是邪恶的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我用php开发的这些年里,我一直听说使用eval()是邪恶的.

In all the years I have been developing in php, I've always heard that using eval() is evil.

考虑以下代码,使用第二个(更优雅的)选项是否有意义?如果没有,为什么?

Considering the following code, wouldn't it make sense to use the second (and more elegant) option? If not, why?

// $type is the result of an SQL statement
// e.g. SHOW COLUMNS FROM a_table LIKE 'a_column';
// hence you can be pretty sure about the consistency
// of your string
$type = "enum('a','b','c')";

// possibility one
$type_1 = preg_replace('#^enum\s*\(\s*\'|\'\s*\)\s*$#', '', $type);
$result = preg_split('#\'\s*,\s*\'#', $type_1);

// possibility two
eval('$result = '.preg_replace('#^enum#','array', $type).';');

推荐答案

在将eval()称为纯邪恶时,我会保持谨慎.动态评估是一种强大的工具,有时可以节省生命.使用eval()可以解决PHP的缺点(见下文).

I would be cautious in calling eval() pure evil. Dynamic evaluation is a powerful tool and can sometimes be a life saver. With eval() one can work around shortcomings of PHP (see below).

eval()的主要问题是:

The main problems with eval() are:

  • 潜在的不安全输入.传递不可信的参数是一种失败的方法.确保参数(或参数的一部分)得到完全信任通常不是一件容易的事.
  • 棘手.使用eval()可使代码更聪明,因此更难以遵循.用布莱恩·科尼根(Brian Kernighan)的话说:"调试是一开始编写代码的两倍.因此,如果您尽可能聪明地编写代码,那么根据定义,您不够聪明,无法调试 "
  • Potential unsafe input. Passing an untrusted parameter is a way to fail. It is often not a trivial task to make sure that a parameter (or part of it) is fully trusted.
  • Trickiness. Using eval() makes code clever, therefore more difficult to follow. To quote Brian Kernighan "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it"

实际使用eval()的主要问题只有一个:

The main problem with actual use of eval() is only one:

  • 没有经验的开发人员,在没有足够考虑的情况下使用它.

根据经验,我倾向于遵循以下原则:

As a rule of thumb I tend to follow this:

  1. 有时eval()是唯一/正确的解决方案.
  2. 在大多数情况下,您应该尝试其他尝试.
  3. 如果不确定,请转到2.
  4. 否则,非常非常小心.
  1. Sometimes eval() is the only/the right solution.
  2. For most cases one should try something else.
  3. If unsure, goto 2.
  4. Else, be very, very careful.

这篇关于什么时候在php中是邪恶的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆