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).';');
eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client.
Definition and Usage The eval() function evaluates a string as PHP code. The string must be valid PHP code and must end with semicolon. Note: A return statement will terminate the evaluation of the string immediately. Tip: This function can be useful for storing PHP code in a database.
JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
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:
The main problem with actual use of eval() is only one:
As a rule of thumb I tend to follow this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With