Search code examples
phpfunctiongettext

Multi-purpose function for gettext translations


It's similar to what Drupal has.

My current function definition is like this:

string t(string $singular, [string $plural, int $number, mixed $arg1, ...])

The order of the arguments doesn't have to follow this pattern. Only string $singular needs to be the first for obvious reasons.

Some examples to demonstrate how it works:

  • Translate "Hello":

    t('Hello')
    
  • Translate "Hello" and format the string (I'm using vsprintf with func_get_args())

    t('Hello %s', $user)
    
  • Plural translation:

    t('%d apple', '%d apples', 5, 5)
    

    So here the problems start. I'm assuming that this is a request for a plural translation if 2nd argument is a string and 3rd argument is integer.

    The issue is that I could intercept a singular translation request by mistake:

    $user = 'Mary';
    t('%s, you need at least %d apples for me to take you srsly', $user, 420)
    

Do you have any suggestions on how could I better implement such functionality and avoid clashes like these?


Solution

  • I would use standard _() and ngettext() instead, because then you could get all localizible strings gathered via xgettext shell command. You could even use your own function names like t() and nt() and still extract them with xgettext (see --keyword param in https://developer.mozilla.org/en/gettext) but you can't (and shouldn't) avoid two functions.