I'm new here and like to join the community to ask & answer!
From the netherlands as a airline pilot student and part-time php programmer :)
At my current project I got a situation in which I call a method from a child class and the parameter's are also defined in a config file. So using the config file info I build up the correct argument order, the variables are defined before that. Now I wanna use eval() to call my method but I get the following error:
A PHP Error was encountered
Message: Object of class Rapport could not be converted to string
$sorteer_optie is the argument I know and the others are already set false, this all seems ok but the eval() call doesn't work.
Think I need to escape it in some way but just putting a backward slash in front of $this won't work..
Ofcourse I could simply send the array to the method but I also call the method in other ways where I strongly dislike the use of an array and I also dislike the option to alternatively accept both the normal way and the array way IF there are better options..
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.