Search code examples
phpeval

When (if ever) is eval NOT evil?


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.

Are there 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.

Summary of Answers:

  • Evaluating numerical expressions (or other "safe" subsets of PHP)
  • Unit testing
  • Interactive PHP "shell"
  • Deserialization of trusted var_export
  • Some template languages
  • Creating backdoors for administers and/or hackers
  • Compatibility with < PHP 5.3
  • Checking syntax (possibly not safe)

Solution

  • Eric Lippert sums eval up over three blog posts. It's a very interesting read.

    As far as I'm aware, the following are some of the only reasons eval is used.

    For example, when you are building up complex mathematical expressions based on user input, or when you are serializing object state to a string so that it can be stored or transmitted, and reconstituted later.