Adding pgettext (gettext context) support to PHP

TL;DR: Packagist Version

It seems the PHP team completely forgot about adding support for gettext context functions, so I implemented them based on what I found in this Stack Overflow answer.

The functions signatures (names and parameters) are what I’m seing in C and Python.

So, if you want to use them – here it is. However, you are probably using composer so you are going to use this:

  1. In your CLI:
    composer require datalinx/gettext-context
  2. Include the vendor/datalinx/gettext-context/src/gettext-context.php file when you need it*

* It’s not added to the autoload directive, since you might not need or want to always include it in runtime. If you want to always load it, just add the source file to your composer.json autoload files list:

    "autoload": {
        "files": [

Now you have pgettext, npgettext, dpgettext, dnpgettext function ready to use in your PHP code.

The functions are documented and fully tested.

Extracting messages with context support

If you are using the xgettext CLI utility, you can add extra keyword parameters to include the context functions. For example, this would be used in our package:

xgettext --force-po --keyword=pgettext:1c,2 --keyword=npgettext:1c,2,3 --keyword=dpgettext:2c,3 --keyword=dnpgettext:2c,3,4 -c -o messages.po tests/Test.php

If you’re using Poedit, add the following keywords in your Catalog > Properties > Sources Keywords:

  • pgettext:1c,2
  • npgettext:1c,2,3
  • dpgettext:2c,3
  • dnpgettext:2c,3,4

Leave a comment

Your email address will not be published. Required fields are marked *