I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )
$fr=array();
$fr['hello']="Bonjour";
I would like to make a function that does the following :
for every word and language function ( $word ="hello",$language="fr")
it would return the right value. So far the way I am doing isn't working
echo $$language[$word];
an开发者_运维问答y ideas? thank you
By default, variables are local to a function. If your dictionary arrays are global, you need to declare them as global, but since the names are variable, you have to access them via $GLOBALS
:
function foo($word, $language) {
echo $GLOBALS[$language][$word];
}
As for a better way, you might want to use just one multi-dimensional array instead of creating one variable for each language:
$dict = array();
$dict['fr']['hello'] = 'Bonjour';
function foo($word, $language) {
global $dict;
echo $dict[$language][$word];
}
A few things to mention here...
I would recommend using actual "locales" (a language code plus country code) to reference your languages rather than your two letter country code. Your example includes "fr" for French. Typical convention is to use locale names instead. For example fr_FR for French (France) and fr_CA for French (Canadien). Language can very greatly based on country (if you're a native US English speaker and take a trip to Australia, you'll understand what I'm talking about).
Depending on the size of your site, you probably don't want to keep this as a PHP dictionary/assoc array. There are lots of options here (putting translations in a database, shared memory, etc.). If you do keep it in PHP memory, opcode caching would be a great idea and is relatively easy to setup. I would encourage you to look at how other frameworks achieve this (and ideally maybe use an existing framework to achieve this).
You mention translating "words". Generally, when internationalizing a site, you want to translate phrases. Translating words and then gluing them together typically results in poor translations.
If you do stick with the dict route, I would highly encourage you to drop the dynamic interpretation of the the variable name/language name in favor of a nested associative array. For example
$dict['fr_FR']['hello'] = 'bonjour';
You might want to consider using a single (nested) array
$strings = array(
"french" => array(
"stringID" => "foobar"
)
);
echo( $strings["french"]["stringID"] );
If you are not utilising a database I would highly recommend looking into this. MySQL and PostgreSQL tend to be popular choices for independent and small development shops.
$$language[$word] didn't work
the work around was
$arr=$$language;
$arr[$word];
精彩评论