28.9. Avoiding eval

Before we get into the gory details, the best way to remember this tip is to remember the catchy phrase eval() is evil. You should do your best to avoid it: eval suffers from slow performance because in order to execute the code, it must invoke the runtime compiler component in the Zend Engine, which is an expensive operation. In many situations, you can replace a call to eval with equivalent code that does not make use of eval.

The most common case where eval can be replaced with faster code is when you use it for accessing variables or functions dynamically. Consider Listing 28.2.

Listing 28.2. Unnecessary use of eval
 <?php function assign($varname, $value) { eval("global \$$varname; \$$varname = \$value;"); } for($i=0; ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.