Sunday, June 22, 2008

Unexpected '}' In Runtime-Created Function

When working the the create_function function in PHP, it's possible to get an error message similar to the following.

Parse error: syntax error, unexpected '}' in /var/www/test.php(36) : runtime-created function on line 1


Now if you're using the return from create_function in an anonymous context you might also get a message like the following.

Warning: preg_replace_callback() [function.preg-replace-callback]: Requires argument 2, '', to be a valid callback in /var/www/test.php on line 36


After getting a Parse Error in the beginning, a subsequent warning can be downright baffling since parse errors generally halt script execution. Apparently parse errors within anonymous, create_function context only halt execution within that context though.

Now when you look into that initial error and the create_function code portion thinking maybe you used a curly brace to end a function call instead of a closing parenthesis and don't see a curly brace anywhere "baffled" can't begin to explain the feeling you might have.

The reason for the initial error likely has to do with a missing semi-colon in the code argument of your create_function call. For instance if your code simply runs the arguments through a function like the following.

$str = preg_replace_callback('#[ACEGIKMOQSUWY]+#', create_function('$a', 'return strtolower($a[0])'), $str);


That seems perfectly fine, however it needs to have the semi-colon to end the function call as in the following.

$str = preg_replace_callback('#[ACEGIKMOQSUWY]+#', create_function('$a', 'return strtolower($a[0]);'), $str);


This fact can be extremely confusing if you've used preg_replace with the e modifier where this ending semi-colon isn't required.

Tip:

preg_replace_callback can be twice or more as fast as preg_replace and the e modifier.

3 comments:

Unknown said...

You saved me this afternoon. Thanks for the tip. :)

shaun said...

Thanks, helped me out as well

Anonymous said...

you´re right ! Thanks