Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore (_) as a PHP function name

Tags:

php

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?

like image 226
user1032531 Avatar asked Dec 05 '12 13:12

user1032531


2 Answers

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.

like image 93
cmbuckley Avatar answered Sep 18 '22 17:09

cmbuckley


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.

like image 37
Shiplu Mokaddim Avatar answered Sep 19 '22 17:09

Shiplu Mokaddim