In all the years I have been developing in PHP, I have 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')";

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

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

推荐答案

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).

The main problems with eval() are:

  • 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"

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

  • Inexperienced developers who use it without enough consideration.

As a rule of thumb I tend to follow this:

  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相关问答推荐

在PHP中替换数组中的文本并同时使用其他函数

wp_enqueue_scripts not loading(基于类的插件)

如何在不指定symfony列的情况下从数据库中获取行数组

PHP日期操作,将多个日期输出为格式化字符串

使用正则表达式搜索两个子字符串(没有重叠/共享字符)

在PHP中读取JSON

当配置的URL为空时禁用Laravel Slack日志(log)记录

PHP:为什么递归需要这么长时间

curl_close()未从PHP 8开始写入CURLOPT_COOKIEJAR会话文件

如何从phpseclib和SFTP获取日志(log)记录?

有没有办法像引用枚举一样引用注册表中的对象?

WooCommerce 以编程方式添加的费用不会持续存在

需要以一种形式执行两个操作

WooCommerce 相关产品(按 children 类别)作为排名数学主要类别的后备

WooCommerce 按产品运输插件:仅收取较高的运输费用

php var_dump(1) 返回字符串(4)

使用php删除数组中相同数字的所有变体

输出每个可能的产品选项

WooCommerce 按 ID 限制产品

Laravel - 关联与设置观察者事件的 ID