Why can I not use a class constant as text domain?

The value of a constant or variable can be evaluated by a PHP parser only. The tool that is used to extract the translatable strings is written in PHP, but is just a string parser. It doesn’t run your code, because that would be too slow and error prone.

Here is an example for how complex that could be:

interface FooTranslate
{
    const TEXT_DOMAIN = 'foo';
}
interface BarTranslate extends FooTranslate {}

class FooBar implements BarTranslate
{
    public function greeting()
    {
        _e( 'hello!', self::TEXT_DOMAIN );
    }
}

(new FooBar)->greeting();

Now find the correct string value for the text domain without executing PHP. Difficult.


You have to use a simple string for all calls to the translation functions.

The developer handbook is telling us that very clearly, unfortunately in the style of an error message and with wrong quotation marks:

Do not use variable names for the text domain portion of a gettext function. Do not do this as a shortcut: __( ‘Translate me.’ , $text_domain );

On a second note: Please do not load your translation files on init. This is expensive: These files are now loaded on every call to AJAX requests, comment submissions and every other file that might not even be related to your plugin. Check the current request context before you are asking WordPress to include a file.

Leave a Comment