Inline evals

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.


7 thoughts on “Inline evals

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

  2. 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)

  3. 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).

  4. Pingback: More inlining « PHP 10.0 Blog

  5. Pingback: faster, better assert « PHP 10.0 Blog

Comments are closed.