Unexpected $end errors in create_function calls

I recently ran across an odd situation while working on a PHP based project. A couple of places I had to use create_function() to create anonymous functions as callbacks for content buffering with ob_start(). After editing one of my anonymous functions I started getting an error similar to this:

Parse error: syntax error, unexpected $end in C:\php\test.php(2) : runtime-created function on line 1

You can recreate this error with the following code:


<?php
$input = 'Hello World';
$callback = create_function('$input', 'return $input; // return input unchanged');
?>

Pretty simple code right? What could be causing the error? Though you would expect a code comment can not create a syntax error, in this case it is the culprit. For some reason create_function doesn't like it when you end with a line-style comment, even if your code is enclosed in a HEREDOC:


<?php
$callback = create_function('$input', <<<HEREDOC
return $input; // this comment causes an error
HEREDOC
);
?>

There are a couple of ways of fixing the error, you can simply remove the comment, or convert it to a block style comment:


<?php
$input = 'Hello World';
$callback = create_function('$input', 'return $input; /* this comment does not cause an error */');
?>

If you are using a HEREDOC you also have the extra option of moving the comment to the line above the last line:


<?php
$callback = create_function('$input', <<<HEREDOC
// this comment does not cause an error
return $input;
HEREDOC
);
?>

It would probably be a good idea to only use block-style quotes inside of create_function code thereby avoiding any chance of causing this frustrating error in the first place.

Previous: Introducing UCSV

Next: A couple of great articles about using OOP in PHP