1

My question is about gettext itself, i kinda don't see the use of a gettext_noop function. I know what it does, but what are the benefits?

If i mark a text with e.g. gettext_noop(), it will not be translated, but xgettext can recognize it, and translation takes place when i output the string as a variable.

Is this because memory usage, or what? Is it better to use it in PHP, or just use _() (or gettext())?

Flimm
  • 136,138
  • 45
  • 251
  • 267
zimpee
  • 11
  • 3

2 Answers2

1

The Gettext manual covers nicely the way gettext_noop may be useful when programming in C.

In PHP, however, it doesn't seem to make sense to do:

$options = array( gettext_noop("one string"),
           gettext_noop("another string") ,);
echo _($options[0]);

It should be perfectly ok to do:

$options = array( _("one string") ,
           _("another string"), );
echo $options[0];

Since PHP is a dynamically typed language, we'd need to be a lot more creative to find a good use for gettext_noop. Most likely, you won't need it in PHP.

That's probably the reason gettext_noop doesn't exist in a vanilla installation and doesn't even figure in PHP's manual.

Roflo
  • 235
  • 1
  • 9
  • 27
0

A use-case for gettext_noop

It can be useful in certain situations. For instance, let's say you've got an array of allowed values for a drop-down in a form:

$allowed_values = ["red", "orange", "blue"];

In the form, you want the user to see the translated values, but for the request to submit the untranslated values:

<select name="color">
<?php foreach ($allowed_values as $allowed_value) : ?>
    <option value="<?= htmlspecialchars($allowed_value) ?>">
        <?= htmlspecialchars(_($allowed_value)) ?>
    </option>
<?php endforeach ?>
</select>

Unfortunately, xgettext can't find the translatable strings, because they haven't been marked. You can mark them like this:

$allowed_values = [_("red"), _("orange"), _("blue")];

But now you can't retrieve the untranslated values later.

Instead, you could do:

$allowed_values = [gettext_noop("red"), gettext_noop("orange"), gettext_noop("blue")];

Now everything can work as intended, as long as you implement the rest of this answer.

How to implement gettext_noop

PHP doesn't actually include gettext_noop by default. To implement it yourself, add this PHP:

function gettext_noop($string)
{
    return $string;
}

And in your invocation of xgettext on the command-line, include this --keyword argument:

xgettext --keyword=gettext_noop ...
Flimm
  • 136,138
  • 45
  • 251
  • 267