You want to display text messages in a locale-appropriate language.
Maintain a message catalog of words and phrases and retrieve the appropriate string from the message catalog before printing it. Example 19-4 shows a simple message catalog with some foods in American and British English and a function to retrieve words from the catalog.
A simple message catalog
Example 19-5 uses the message catalog to print out a list of foods.
Using the message catalog
Example 19-5 prints:
My favourite foods are: chips crisps sweets
To have Example 19-5 output in American English instead of British English, just set $LANG to en_US.
You can combine the msg( ) message retrieval function with sprintf( ) to store phrases that require values to be substituted into them. For example, consider the English sentence "I am 12 years old." In Spanish, the corresponding phrase is "Tengo 12 años." The Spanish phrase can't be built by stitching together translations of "I am," the numeral 12, and "years old." Instead, store them in the message catalogs as sprintf( )-style format strings, as in Example 19-6.
A sprintf( )-style message catalog
Example 19-7 passes the results of msg( ) to sprintf( ) as a format string.
Using a sprintf( )-style message catalog
Example 19-7 prints:
Tengo 12 años.
For phrases that require the substituted values to be in a different order in a different language, sprintf( ) supports changing the order of the arguments. This is shown in Example 19-8.
Changing message catalog argument order
With either language, call sprintf( ) with the same order of arguments (i.e., first years, then months), as in Example 19-9.
Using a message catalog with variable argument order
Example 19-9 prints:
I am 12 years and 7 months old. Tengo 7 meses y 12 años.
In the format string, %2$ tells sprintf( ) to use the second argument, and %1$ tells it to use the first.
These phrases can also be stored as a function's return value instead of as a string in an array. Storing the phrases as functions removes the need to use sprintf( ). Example 19-10 shows some functions that return entire sentences.
Message catalog functions
If some parts of the message catalog belong in an array, and some parts belong in functions, an object is a helpful container for a language's message catalog. Example 19-10 contains a base object and two simple message catalogs.
Message catalog objects
Each message catalog object extends the pc_MC_Base class to get the msg( ) method, and then defines its own messages (in its constructor) and its own functions that return phrases. Example 19-12 uses the message catalog object to print text in Spanish.
Using a message catalog object
To print the same text in English, $MC just needs to be instantiated as a pc_MC_en_US object instead of a pc_MC_es_US object. The rest of the code remains unchanged.
19.4.4. See Also
The introduction to Chapter 7 discusses object inheritance; documentation on sprintf( ) at http://www.php.net/sprintf.