php语言翻译功能 [英] php function for language translation
问题描述
对于CMS的多语言使用,它们通过类似于以下功能的功能来翻译术语
For multi-language usage of CMS, they translate terms by a function similar to
function __($word) {
include 'fr.php';
if(!empty($lang[$word])) {$translated=$lang[$word];
} else {
$translated = $word;
}
return $translated;
}
-
由于我们需要在php页面中多次使用此功能,因为所有单词和短语都将被__('')回显;该函数是否需要每次都包含语言时间,否则将在首次加载后为该函数缓存?
Since we need to use this function several times in a php page, as all words and phrases will be echoed by __(' '); does the function need to include the language time every time, or it will be cached for the function after first load?
由于语言文件包含整个网站上使用的单词和短语的完整列表(数千个键/值),因此pho需要在每次访问页面时将此长数组加载到内存中.将多语言功能添加到CMS真的是最好的方法吗?
Since the language file contains a complete list of words and phrased used throughout the website (thousands of key/value), pho needs to load this long array into memory every time a page is visited. Is it really the best approach to add multi-language feature to a CMS?
推荐答案
如果由于某种原因而不能使用gettext()
,那么最好将类似这样的东西放在带有gettext()
的对象中包含语言字符串作为静态数组,例如:
If you can't use gettext()
for some reason, you'd be better off, with something like this, to put it into an object with the included language strings as a static array, something like:
class Message {
private static $_messages = array();
public static function setMessageLibrary($sMessageLibrary) {
require_once $sMessageLibrary;
self::$_messages = $aMsgs;
}
public static function getMessage($sMessageId) {
return isset(self::$_messages[$sMessageId]) ? self::$_messages[$sMessageId] : "";
}
}
您的消息库文件(包含在setMessageLibrary()
静态函数中),每种语言都将包含一个消息库文件,其中需要一个名为$aMsgs
的变量,该变量可能类似于:
Your message library file (included with the setMessageLibrary()
static function), of which you'll have one per language, will need a variable in it called $aMsgs
which might look something like:
// Messages for fr-FR
$aMsgs = array(
'hello_everybody' => "Bonjour tout le monde"
...
and so on
);
由于全部是静态的,但是在对象内部,因此可以通过在脚本的开头进行设置来有效地缓存包含的语言文件.
Since it's all static but within the object you can effectively cache that included language file by setting it at the start of your script.
<?php
Message::setMessageLibrary('/lang/fr-FR/messages.inc.php');
echo Message::getMessage('hello_world');
echo Message::getMessage('another_message');
echo Message::getMessage('yet_another_message');
?>
然后,所有三个消息将引用存储在Message::$_messages
All three messages will then reference the single language array stored in Message::$_messages
这里没有卫生措施,也没有健全性检查,但这仍然是基本原则……如果您不能使用gettext();)
There's no sanitisation, nor sanity checks in there, but that's the basic principle anyway ... if you can't use gettext() ;)
这篇关于php语言翻译功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!