[thelist] Re: eval stuff

Simon Willison simon at incutio.com
Tue Jul 16 04:10:00 CDT 2002


At 15:03 16/07/2002 +0900, you wrote:
>In PHP for instance, eval() will allow me to replace a variable in a string
>very easily. The only alternative would be to manually replace a string
>value, which is not a variable. e.g.,
>
>WITH EVAL
>
>     // In messages.inc file
>     $message001 = "Something before $variable and something after.";
>
>     // In the code..
>     include "messages.inc" ;
>     $variable = "testing";
>     eval ("\$message001 = \"$message001\";");
>
>
>WITHOUT EVAL
>
>     // In messages.inc file
>     $message001 = "Something before _  and something after.";
>
>     // In the code..we need to replace that underscore with a value
>     include "messages.inc" ;
>     $variable = "testing";
>     $message001 = str_replace("_", $variable, $message001);

Here's an alternative that's as effective and simple as the eval() version:

// In messages.inc
$messag001 = "Something before %s and something after.";

// In the code
include('messages.inc');
$variable = 'testing';
$message001 = sprintf($message001, $variable);

The performance hit from eval() in server side languages such as PHP is
actually pretty big. Most of these languages work by having a parser which
parses the code in to some kind of parse-tree, then an interpreter which
goes through the parse tree line-by-line executing the commands. When PHP
hits an eval() function it will be operating in interpreter mode, but will
then be forced to jump back in to parse mode to analyse the string, before
jumping back again in to interpreter mode to execute it. This is a much
bigger performance hit than calling a function such as str_replace() or
sprintf().

Regards,

Simon Willison
http://www.bath.ac.uk/




More information about the thelist mailing list