tags:

views:

630

answers:

13

I've heard many places that PHP's eval function is often not the answer. In light of PHP 5.3's LSB and closures we're running out of reasons to depend on eval or create_function.

Is there is any conceivable cases where eval is the best (only?) answer in PHP 5.3?

This question is not about whether eval is evil in general, as it obviously is not.

+2  A: 

If you are writing a site that interprets and executes PHP code, like an interactive shell would.

...

I'm a systems guy, that's all I got.

Ed Swangren
This kind of application would be hard to sandbox (if possible at all), and would *have* to require admin access to use. If the user is required to have admin access, there is little-to-no reason for them not to just edit a `.php` files directly or fire up `php -a`.
Kendall Hopkins
@Ken I don't see what "admin access" has to do with anything here.
Artefacto
@Kendall Hopkins: These applications already exist.
Ed Swangren
@Ed Swangren Link?
Kendall Hopkins
http://try-python.mired.org/ http://www.ruby.ch/interpreter/rubyinterpreter.shtml http://blog.arpitnext.com/2009/08/codepad-online-compiler-interpreter-run.html - there are three
Ed Swangren
+1  A: 

An appropriate occasion (given the lack of easy alternatives) would be when trusted data was serialized with var_export and it's necessary to unserialize it. Of course, it should never have been serialized in that fashion, but sometimes the error is already done.

Artefacto
+8  A: 

If you're writing malware and you want to make life hard for the sysadmin who's trying to clean up after you. That seems to be the most common usage case in my experience.

tylerl
While it's valid use, the language probably should be offering solutions for that kind of problem :P
Kendall Hopkins
Eval isn't the half of it -- http://stackoverflow.com/questions/3115559/
tylerl
+1  A: 

I suppose, eval should be used where the code is actually needs to be compiled. I mean such cases like template file compilations (template language into PHP for the sake of performance), plugin hook compilation, compilations for performance reasons etc.

FractalizeR
Most popular templating engines (smarty and twig) have found that it way faster to write the PHP code to a file that way it can take advantage of opcode caching. It'd have to be a pretty crazy templating system to *require* run time building of template code.
Kendall Hopkins
VBulletin Plugin System and templates are an example of what I've said.
FractalizeR