我正在制作一个将被翻译成 x 种语言的网站。
所有字符串都必须本地化。
有时我需要显示从数据库中检索到的语言名称、国家名称或其他信息。以这种方式处理的数据很少会改变 - 如上所述,我正在谈论语言名称,国家等。
在此示例中,我使用的数组包含站点 UI 已翻译成的语言。为了允许翻译名称(当“更改语言”标志/链接悬停时用于标题文本),我有一个像*这样的数组:
Array("zh_CN" => _("Chinese - Simplified"), "en_GB" => _("English"));
我使用它们来获取给定语言的相关名称字符串。
目前我正在使用一个全局数组:
$global_langNames = Array("zh_CN" => _("Chinese - Simplified"), "en_GB" => _("English"));
用法:
global $global_langNames;
echo $global_langNames[$code]; // $code = 'zh_CN'
输出(语言环境 = en_GB):
简体中文
输出(语言环境 = zh_CN):
简体中文</p>
我更愿意将这个(和其他)常量数组声明为类的私有成员,但似乎 PHP 不愿意:
class constants_lang{
private static $langNames = Array("zh_CN" => _("Chinese - Simplified"), "en_GB" => _("English"));
static function getLangName($code){
return self::$langNames($code);
}
}
结果是:
Parse error: syntax error, unexpected '(', expecting ')' in /site/http/includes/classes/constants/lang.php on line 20
我应该低头回到全局数组,还是有另一种更好的方法让我以这种方式使用“常量”数组?
*数组键来自存储语言代码的数据库表以及我们是否有UI翻译:
code ui translation
zh_CN 1
en_GB 1
zh_TW 0
....
解决方案
class constants{
private $langNamesFromCode;
function __construct()
{
$this->langNamesFromCode = $this->initLangNamesFromCode();
}
/* INIT */
private static function initLangNamesFromCode()
{
return Array("zh_CN" => _("Chinese - Simplified"), "en_GB" => _("English"));
}
/* GETTERS */
public static function getLangNameFromCode($code)
{
if(self::isStatic()){
$langNamesFromCode = self::initLangNamesFromCode();
return $langNamesFromCode[$code];
}
else{
return $this->langNamesFromCode[$code];
}
}
/* UTILITY */
private static function isStatic()
{
return !(isset($this) && get_class($this) == __CLASS__);
}
}