May 19, 2007

create_function() is not your friend, buddy

While browsing through PHP Developer today, I came across this blog entry: "My new best friend" extolling the virtues of create_function(). Let me tell you why create_function() is not my best friend...

First, despite the disclaimer in the mentioned blog entry, it is as bad as its kissing-cousin eval(). Let's take a look at what create_function() actually does by translating it into userland code:

function create_function($args, $code)
{
static $id = 0;
eval("function __lambda_func($args) { $code }");
while (!runkit_function_rename('__lambda_func', "\0lambda_" . (++$id)));
return "\0lambda_$id";
}

I'll let you contemplate on that awhile....You should be noticing the following sets of problems:

  • Prone to critical abuse by user-supplied code
  • Skips opcode cache optimizations

You should also be thinking about the practical issues with it:

  • Code lives inside quoted strings which means awkward escaping of embedded quotes
  • Encourages not using comments (evil)
  • 100% blind to reflection or PHPDoc style documentation generation
  • I'm sure you can come up with a couple more...

"If eval() is the answer, then you're asking the wrong question"

1 comment:

Note: Only a member of this blog may post a comment.