16.5. Localizing Text Messages16.5.2. SolutionMaintain a message catalog of words and phrases and retrieve the appropriate string from the message catalog before printing it. Here's a simple message catalog with some foods in American and British English and a function to retrieve words from the catalog:
16.5.3. DiscussionThis short program uses the message catalog to print out a list of foods:
To have the program 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:
You can then pass the results of msg( ) to sprintf( ) as a format string:
For phrases that require the substituted values to be in a different order in different language, sprintf( ) supports changing the order of the arguments:
With either language, call sprintf( ) with the same order of arguments (i.e., first years, then months):
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( ). Functions that return a sentence look like this:
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. A base object and two simple message catalogs look like this:
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. Here's how to print text in Spanish:
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. 16.5.4. See AlsoThe introduction to Chapter 7 discusses object inheritance; documentation on sprintf( ) at http://www.php.net/sprintf.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|