Many people say it is bad practice to use the eval() procedure in any language. That there is always a better way to do it. I disagree.
I think that some situations can warrent the use of the eval() procedure. Esspecially if you use it properly and carefully.
The PHP eval() procedure is no different. There are two important rules to remember when using PHP's eval().
- Always check the the return value from eval().
- Make it so you "code" returns an "OK" signal when it is done.
Let me explain this more. Since you are using "executing" unknown code and really don't know if the code has any syntax errors, or and other errors. You should be making an effort to check for this.
The PHP eval() procedure will return FALSE if there us an error. Therefore, you should check to see if it returns FALSE. So, you should be doing something like:
if ( FALSE === eval($code) ) {
// Error.
// ... handle the error ...
}
However, it is possible that eval() could return FALSE, even if it did not have this kind of error. So, you must set up your code so returns something other than FALSE when there is no error. I suggest it returns TRUE. You can do this by doing something like:
$code .= 'return TRUE;';
if ( FALSE === eval($code) ) {
// Error.
// ... handle the error ...
}
That way you know if everything went OK, then it will return TRUE.
So, for a fuller example we might have something like:
// This procedure returns a string that is legal PHP expression.
$variable_code = get_variable_code();
$code = '$a = ' . $variable_code . ';';
// $code = "\$a = $variable_code;";
$code .= 'return TRUE;';
if ( FALSE === eval($code) ) {
// Error.
// ... handle the error ...
}
You can do alot more interesting things with eval() too.
Comments
No known comments. (There may be some out there though.)