O'Reilly logo

Core PHP Programming, Third Edition by Leon Atkinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required