GotText v2.0.3 - API reference

GotText - a translation engine with gettext-like features. https://github.com/alkatrazstudio/gottext

Copyright: 2016, Alkatraz Studio https://alkatrazstudio.net
License: GNU General Public License version 3 or later
Author: Alexey Parfenov aka ZXED zxed@alkatrazstudio.net
Methods summary (click to expand)
public
# __construct( string $filename = null, string $data = null )

Constructs GotText object.

Constructs GotText object.

Loads a file with translations. The file can be any file that can be opened using fopen().

Throws Exception on error.

All loaded files are cached in memory, so the next time the file is requested it's loaded from memory, not from disk. The memory cache is per-process, e.g. all scripts that were loaded by the same PHP process will share the same memory cache.

The memory cache is a key-value storage where a key is a filename passed to a GotText constructor. To load a file from cache the GotText must be created with the same exact filename string that was used to load a file for the first time. It means that if you load two files ./tr/ru_RU.mo and ./tr/../tr/ru_RU.mo, then GotText will load the same file from disk twice and create two different cache entries in memory.

GotText will never automatically reload a file from disk even if the file is changed or even deleted. To reload a file use GotText::reload(). To unload a file from memory use GotText::unload(). To see all previously loaded files use GotText::getFilenames(). All these functions still only apply to a current PHP process.

GotText can also load translations from raw binary string data. Pass the data as a second parameter. In this case you may specify any arbitrary string for a filename, which can be later used to refer to that data, i.e. in GotText::get().

Note that GotText will ignore any plural form rules found in MO file. All plural form rules are hardcoded into GotText. The only information GotText will retrieve and use from MO file header is a locale code.

Parameters

$filename

A file with translations to load in gettext MO format. If not specified then a dummy GotText will be returned. See GotText::isDummy() to read more about dummy objects.

$data

A binary data in gettext MO format. If this parameter is specified, then filename can be any arbitrary string. The translations are always reloaded from this data when this parameter is specified.

Example

<?php
// loading from file
try{
    $gotText = new GotText("./ru_RU.mo");
}catch(Exception $e){
    error_log($e->getMessage());
    $gotText = new GotText();
}
echo $gotText->_("Hello"), "\n";

// loading from string data
try{
    $data = file_get_contents("./ja_JP.mo")
    $gotText2 = new GotText("Japanese", $data);
}catch(Exception $e){
    error_log($e->getMessage());
    $gotText2 = new GotText();
}
echo $gotText2->_("Hello"), "\n";

// loading the previous translations from "Japanese" string data
$gotText3 = GotText::get("Japanese");
if(!$gotText3) // if the translations can not be loaded
    $gotText3 = new GotText(); // then don't translate anything
echo $gotText3->_("Hello"), "\n";

// loading from URL
try{
    $gotText4 = new GotText("http://example.com/sv_SE.mo");
}catch(Exception $e){
    error_log($e->getMessage());
    $gotText4 = new GotText();
}
echo $gotText4->_("Hello"), "\n";

public string
# _( string $msgid )

Translates a string.

Translates a string.

Similar to gettext(msgid).

Parameters

$msgid
A string to translate.

Returns

string
The translation of msgid, or msgid if no translation found.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo $gotText->_("Hello"); // "Привет"

public string
# _n( string $msgid, string $msgid_plural, integer $n )

Translates a string and chooses a plural form.

Translates a string and chooses a plural form.

Similar to ngettext(msgid, msgid_plural, n).

Parameters

$msgid
A string to translate.
$msgid_plural
A plural form of msgid for the default language (English).
$n
A number to choose a plural form for. Currently only positive integers are handled correctly.

Returns

string

The plural translation of msgid for the number n. If no translation is found then the function returns msgid if n == 1, or msgid_plural if n != 1.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo sprintf($gotText->_n("%d book", "%d books", 1), 1); // "1 книга"
echo sprintf($gotText->_n("%d book", "%d books", 2), 2); // "2 книги"
echo sprintf($gotText->_n("%d book", "%d books", 5), 5); // "5 книг"

public string
# _p( string $msgid_ctxt, string $msgid )

Translates a string using a provided context.

Translates a string using a provided context.

Behaves like GotText::_(), but also takes a message context msgid_ctxt into account. Similar to pgettext(msgid_ctxt, msgid).

Parameters

$msgid_ctxt
A context to look for msgid in.
$msgid
A string to translate.

Returns

string
The translation of msgid in the provided context msgid_ctxt, or msgid if no such translation found.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo $gotText->_("Title"); // "Название"
echo $gotText->_p("Person", "Title"); // "Титул"

public string
# _np( string $msgid_ctxt, string $msgid, string $msgid_plural, integer $n )

Translates a string using a provided context and chooses a plural form.

Translates a string using a provided context and chooses a plural form.

Behaves like GotText::_n(), but also takes a message context msgid_ctxt into account. Similar to npgettext(msgid_ctxt, msgid, msgid_plural, n).

Parameters

$msgid_ctxt
A context to look for msgid in.
$msgid
A string to translate.
$msgid_plural
A plural form of msgid for the default language (English).
$n
A number to choose a plural form for. Currently only positive integers are handled correctly.

Returns

string

The plural translation of msgid in the provided context msgid_ctxt for the number n. If no translation is found then the function returns msgid if n == 1, or msgid_plural if n != 1.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo sprintf($gotText->_np("Web", "%d site", "%d sites", 5), 5); // "5 сайтов"
echo sprintf($gotText->_np("Location", "%d site", "%d sites", 5), 5); // "5 мест"

public boolean
# isDummy( )

Checks if it's a dummy GotText object.

Checks if it's a dummy GotText object.

Dummy GotText objects contain no translations and are usually used as stubs when loading a MO file fails. GotText object with a valid file loaded can become a dummy object if the corresponding file is later unloaded from memory via GotText::unload().

Be careful when using functions like GotText::getPluralsCount(), GotText::pluralFunc() or similar functions. Such functions will always return an empty string or a zero for dummy objects. See the example below.

Returns

boolean
TRUE if the GotText object is a dummy object.

Example

<?php
try{
    $gotText = new GotText("./invalid.lang.file");
}catch(Exception $e){
    // construct a fallback dummy object
    $gotText = new GotText();
}
// the following will not fail
// even if the translation file was not loaded
echo $gotText->_("Hello"); // "Hello"
var_export($gotText->isDummy()); // true
var_export($gotText->getPluralsCount()); // 0
var_export($gotText->pluralFunc(3)); // 0
var_export($gotText->getFilename()); // ""
var_export($gotText->getLocaleCode()); // ""

// load a valid file, then unload it
$gotText = new GotText("./ru_RU.mo");
var_export($gotText->isDummy()); // false
echo $gotText->_n("%d book", "%d books", 3); // "%d книги"
GotText::unload("./ru_RU.mo");
var_export($gotText->isDummy()); // true
echo $gotText->_n("%d book", "%d books", 3); // %d books
var_export($gotText->getPluralsCount()); // 0
var_export($gotText->pluralFunc(3)); // 0
var_export($gotText->getFilename()); // "./ru_RU.mo"
var_export($gotText->getLocaleCode()); // ""

public static
# reload( string $filename )

Reloads a translation file.

Reloads a translation file.

Purges the memory cache for the file and loads it from disk updating the memory cache. This function will affect all GotText instances in all scripts that are currently running or will be running in the current PHP process.

Throws Exception on error.

This function will reload a translation file only for the current PHP process. You may want to use GotText::getTimeCached() in each process to check if the file needs to be reloaded in that process.

To reload a binary data use

new GotText($filename, $data);

instead of this function. See GotText::__construct() for more details.

Parameters

$filename
A file to reload from disk.

Example

<?php
// let's assume that all scripts below are loaded from the same PHP process

<?php // script test.php loads the file
$gotText = new GotText("./ru_RU.mo");
echo $gotText->_("Hello"); // "Привет"

// let's assume that the file ./ru_RU.mo has been changed on disk
// the translation of "Hello" was changed to "Здравствуйте"
// still every consecutive invocation of test.php will yeild the same result "Привет"
// it's because the file is now loaded from memory, not from disk

<?php // script reset.php reloads the file from disk
GotText::reload("./ru_RU.mo");

<?php // script test.php loads the file
// still from memory, but now with the new contents
$gotText = new GotText("./ru_RU.mo");
echo $gotText->_("Hello"); // "Здравствуйте"

public static
# unload( string $filename )

Unloads a translation file from memory.

Unloads a translation file from memory.

Almost the same as GotText::reload() but does not load the contents after cleaning the memory cache. Next time GotText loads the file it will load it from disk, not memory. All consecutive loads will be again from memory.

If the file was not loaded in the first place, then this function does nothing.

If PHP runs scripts simultaneously in several threads in one process, then this function may unload all translations from a given file in the middle of some other scripts, which will cause these scripts to output untranslated messages until some thread loads this file again.

Therefore the use of this function in multi-threaded implementations is discouraged.

The memory is not entirely cleared when calling this function. Instead, the GotText object is replaced by a dummy GotText object with no data (see GotText::isDummy()). It means that each unloaded translation file will still occupy a small amount of memory (less that 500 bytes)

This function will unload a translation file only from the current PHP process. You may want to use GotText::getTimeCached() in each process to check if the file needs to be unloaded in that process.

Parameters

$filename
A file to unload from memory.

Example

<?php
// let's assume that all scripts below are loaded from the same PHP process
// and it's a multi-threaded PHP implementation

<?php // script test.php starts
$gotText = new GotText("./ru_RU.mo");
echo $gotText->_("Hello"); // "Привет"

// at this point of time, some other script invokes
// GotText::unload("./ru_RU.mo")

// script test.php is still running, but all translations are now unloaded
echo $gotText->_("Hello"); // "Hello"

public static GotText
# get( string $filename )

Creates GotText object if the file is already cached in memory.

Creates GotText object if the file is already cached in memory.

Checks if the file with the specified filename is in the memory cache. If the translations are found in memory, then a new GotText object is created and returned. If there's no such file loaded in memory, then the function returns FALSE.

This function will also return FALSE if the file is currently unloaded by GotText::unload().

Parameters

$filename
A filename that refers to a desired translation file.

Returns

GotText

A GotText object if the file is found in memory. FALSE if the file was not loaded before or if it's currently unloaded.

Example

<?php
$langId = "Russian";
$gotText = GotText::get($langId);
if(!$gotText)
{
    $data = file_get_contents("./ru_RU.mo");
    $gotText = new GotText($langId, $data);
}

public array
# getStrings( )

Returns internal dictionary data.

Returns internal dictionary data.

Builds and returns an associative array containing all dictionaries for the currently loaded translation resource.

Returns

array
A dictionary data.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
var_export($gotText->getStrings());

// the output will be something like this
array (
  'singular' =>
  array (
    'Title' => 'Название',
    '' => 'Project-Id-Version:
POT-Creation-Date: 2016-01-25 20:56+0300
PO-Revision-Date: 2016-01-26 01:00+0300
Last-Translator:
Language-Team:
Language: ru_RU
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Generator: Poedit 1.8.4
X-Poedit-Basepath: .
Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);
X-Poedit-KeywordsList: __;_n:1,2;_p:1c,2;_np:1c,2,3
X-Poedit-SearchPath-0: test.php
',
  ),
  'plural' =>
  array (
    '%d site' =>
    array (
      0 => '%d место',
      1 => '%d места',
      2 => '%d мест',
    ),
  ),
  'singular_context' =>
  array (
    'Person' =>
    array (
      'Title' => 'Титул',
    ),
  ),
  'plural_context' =>
  array (
    'Web' =>
    array (
      '%d site' =>
      array (
        0 => '%d сайт',
        1 => '%d сайта',
        2 => '%d сайтов',
      ),
    ),
  ),
)

public static array
# getFilenames( )

Return a list of filenames of all previously loaded files.

Return a list of filenames of all previously loaded files.

This list will also include filenames of all files that are currently unloaded by GotText::unload(). To check if the file is actually loaded into memory use GotText::get().

Returns

array
An array of filenames. The returned filenames will be exactly the same strings that were passed to GotText::__construct().

Example

<?php
// let's assume that all scripts below are loaded from the same PHP process

<?php // script test1.php loads the first file
$gotText = new GotText("./ru_RU.mo");

<?php // script test2.php loads the second file
$gotText = new GotText("Swedish", file_get_contents("./sv_SE.mo"));
GotText::unload("Swedish");

<?php // script test3.php loads no translations
$gotText = new GotText();

<?php // script result.php shows filenames of all currently loaded files
$filenames = GotText::getFilenames();
var_export($filenames);

// the output will be
array (
  0 => './ru_RU.mo',
  1 => 'Swedish',
)

public integer
# pluralFunc( integer $n )

Retrieves the plural form index for a given number.

Retrieves the plural form index for a given number.

Returns a zero-based index of a plural form for a given number n.

This function will always return zero for a dummy GotText object (see GotText::isDummy()).

Parameters

$n
A number. Currently only positive integers are handled correctly.

Returns

integer
A plural form index.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
$pluralForms = array("%d книга", "%d книги", "%d книг");
$number = 22;
$pluralFormIndex = $gotText->pluralFunc($number); // 1
$pluralForm = $pluralForms[$pluralFormIndex]; // "%d книги"
echo sprintf($pluralForm, $number); // "22 книги"

$dummy = new GotText();
echo $dummy->pluralFunc(42); // 0

public integer
# getTimeCached( )

Returns the time the current file was cached in memory.

Returns the time the current file was cached in memory.

Returns the timestamp the translations in the current file were last reloaded and put in memory cache.

This function will always return zero for a dummy GotText object (see GotText::isDummy()).

Returns

integer
A UNIX timestamp.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
// reload the file if it was changed on disk since the last caching
if($gotText->getTimeCached() < filemtime($filename))
    GotText::reload($filename);

$dummy = new GotText();
echo $dummy->getTimeCached(); // 0

public string
# getFilename( )

Returns the filename associated with the the currently loaded file.

Returns the filename associated with the the currently loaded file.

The returned filename will be exacly the same string that was passed to GotText::__construct().

Returns

string

The filename of the currently loaded resource.

<?php
$gotText = new GotText("./ru_RU.mo");
echo $gotText->getFilename(); // "./ru_RU.mo"
GotText::unload("./ru_RU.mo");
echo $gotText->getFilename(); // "./ru_RU.mo"

$dummy = new GotText();
echo $dummy->getFilename(); // ""
public string
# getLocaleCode( )

Returns the locale code.

Returns the locale code.

Returns the locale code for the current locale. This value is taken from the Language header of MO file.

This function will always return an empty string for a dummy GotText object (see GotText::isDummy()).

Returns

string
A locale code.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo $gotText->getLocale(); // "ru_RU"

$dummy = new GotText();
echo $dummy->getLocaleCode(); // ""

public integer
# getPluralsCount( )

Returns the number of plural forms.

Returns the number of plural forms.

Returns the number of plural forms for the language/locale in the currently loaded file. The number of plural forms is hardcoded for each language/locale and may not correspond with data found in MO file headers.

This function will always return zero for a dummy GotText object (see GotText::isDummy()).

Returns

integer
A number of plural forms.

Example

<?php
$gotText = new GotText("./ru_RU.mo");
echo $gotText->getPluralsCount(); // 3

$dummy = new GotText();
echo $dummy->getPluralsCount(); // 0

public static array
# getInfo( )

Returns some information about GotText extension.

Returns some information about GotText extension.

Returns version information, build timestamp and build options.

Returns

array

An associative array with the following fields:

  • major - major version number (1.2.3);
  • minor - minor version number (1.2.3);
  • patch - patch version number (1.2.3);
  • timestamp - build timestamp;
  • thread_safe - TRUE if GotText is thread-safe (THREAD_SAFE build flag);
  • native_file - TRUE if GotText uses native file functions instead of fopen() (NATIVE_FILE build flag);
  • debug - TRUE if this is a debug version of GotText (DEBUG build flag);
  • boost_regex - TRUE if Boost.Regex is used instead of built-in GCC regular expression library (BOOST_REGEX build flag).
  • standalone - TRUE if GotText is compiled as a standalone library (STANDALONE build flag).

Example

<?php
var_export(GotText::getInfo());

// will output something like this
array (
  'major' => 1,
  'minor' => 0,
  'patch' => 2,
  'timestamp' => 1456753020,
  'thread_safe' => false,
  'native_file' => false,
  'debug' => false,
  'boost_regex' => true,
  'standalone' => true,
)

API documentation generated by ApiGen