8

According to http://php.net/manual/en/functions.user-defined.php, I should be able to use an underscore (_) as a function name:

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

However, the following kills my program without causing any errors:

error_reporting(E_ALL);
echo('start');
function _($x){return ($x)?htmlspecialchars($x):'nbsp;';}
echo('end');

I am using PHP Version 5.3.18. What don't I understand?

9
  • Do you have error reporting turned on? Commented Dec 5, 2012 at 13:09
  • 5
    use double underscore instead __($x) Commented Dec 5, 2012 at 13:09
  • The above code worked for me. (PHP Version 5.3.10) Commented Dec 5, 2012 at 13:10
  • 3
    If you had error reporting turned on, you would have seen an error about redeclaring _() Commented Dec 5, 2012 at 13:11
  • 1
    @user1032531 Try 3v4l.org/l5d2i Commented Dec 5, 2012 at 13:14

2 Answers 2

17

There is already a built-in function called _; it is an alias for gettext.

You are likely getting a Fatal error: Cannot redeclare _(), but the error may not be output to your screen depending on your setting for display_errors. You could also look at the log_errors directive.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Never knew that. Not documented very well: php.net/manual/en/function.gettext.php. Why isn't it throwing some sort of error?
@user1032531 It does: PHP Fatal error: Cannot redeclare _()
You must have error reporting turned off. I get this output: PHP Fatal error: Cannot redeclare _() in foo.php on line 3
4

As cbuckley said, there is already a gettext alias defined with name _. If you have gettext enabled _ name is taken.

You better use double underscore (__). I use it frequently. Or you disable gettext.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.