PHP 10.0 Blog

What if…

Inline evals

Posted by Stas on October 16, 2006

Eval function in PHP allows to dynamically create code, which is neat (for people that like such things ;)

= “foo”;
“\$foo = $classname::bar;”);

However, there’s a problem with that – it’s slow. It means each time one has to compile code anew and then execute it anew. Slowwww. There’s another method – create_function() – which allows to do like this:

= create_function(‘$a,$b’, ‘return “ln($a) + ln($b) = ” . log($a * $b);’);
“New anonymous function: $newfunc\n”;
$newfunc(2, M_E) . “\n”;

But the problem would be that it creates a new function – meaning, you can not share symbol table with this code, and you need brand new execution context each time you call it, which is slow too. So, won’t it be nice if you could combine best of the two functions and have code that can be compiled once, but run a number of times while sharing symbol table with the calling code? Would work almost like lambda – though not exactly like – it would not bind variables until really executing the code.
But, if we could use both benefits of create_function() as to making function objects and compiling it only once – and of instant same-scope-ness of eval() – it might allow to do some nice things.

About these ads

7 Responses to “Inline evals”

  1. [...] Inline evals [...]

  2. [...] Inline evals [...]

  3. sor said

    Ever heard of

    $foo = constant(“{$classname}::bar”)

    ? :)

  4. Stas said

    That would probably work, but that was just an example. People do a lot of things with evals (though I personally don’t like it too much because it’s so expensive).

  5. Rodrigo Fuentealba said

    Every time you use eval’d expressions, God kills a kitten. Shouldn’t be used unless you *really* know what you’re doing!!

    (Yeah, there’s a lot of people who uses eval’d expressions, but there’s also a lot of people who uses Microsoft Windows in their computers)

  6. analytik said

    and there’s also too many kittens in the world.

  7. Amir Laher said

    I agree that there’s too many kittens, but eval is just hackish and hard to maintain. 99.9 times out of 100 there’s a better way of doing things.
    ‘Reflection’ solves very many of these issues …
    $classname = “foo”;
    $ref= new ReflectionClass($classname);
    echo $ref->getProperty(‘bar’)->name;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: