View Single Post
11-28-2011, 11:15 AM
Join Date: Nov 2011
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 shortcommings 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.
• Trickyness. 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 mentioned before eval() can help you do things that are impossible in pure PHP. My favourite trick involving dynamic evaluation enables static calls on variable classes. Since $foo::bar() is illegal in PHP, below solution works around that limitation.
$className = 'Foo';
eval('$result = ' . $className . '::bar()');
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.
View Public Profile
Send a private message to Parkinson4
Find More Posts by Parkinson4