This project is an implementation of gettext in PHP 5.5.
Before starting, make sure every file is properly included, preferably using an auto loader.
- Construct a new MO object. The constructor takes a string argument containing a .mo file
file_get_contents
can be used to supply such a file.
$mo = new \gettext\MO(file_get_contents('my_file.mo'));
- Translate a string. This is equivalent to PHP's
gettext
function.
$translatedString = $mo->translate('My string.');
- Translate a plural string. Equivalent to PHP's
ngettext
function. (Note that thetranslate
method does not automatically substitute %d. Use something likesprintf
.)
$numberOfStrings = 2;
$pluralString = $mo->translate('One string.', '%d strings.', $numberOfStrings);
The translate
method accepts a fourth argument to set the translation's domain.
The equivalent to dgettext
is therefore:
$domain = 'my_domain';
$translatedString = $mo->translate('My string.', null, null, $domain);
While the equivalent to dngettext
is:
$pluralString = $mo->translate('One string.', '%d strings.', $numberOfStrings, $domain);
It's possible to merge MO objects to support spreading translations over multiple files. To merge two MOs simply call the merge
method, this will merge the second MO into the first.
$mo1 = new \gettext\MO(file_get_contents('my_file_1.mo'));
$mo2 = new \gettext\MO(file_get_contents('my_file_2.mo'));
$mo1->merge($mo2);