php function for language translation

非 Y 不嫁゛ 提交于 2019-12-13 12:17:58

问题


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;
}
  1. 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?

  2. 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?


回答1:


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] : "";
  }
}

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');
?>

All three messages will then reference the single language array stored in Message::$_messages

There's no sanitisation, nor sanity checks in there, but that's the basic principle anyway ... if you can't use gettext() ;)




回答2:


1) it won't be cached, use include_once instead

2) no, i think gettext is doing it another/better way




回答3:


  1. IIRC, it will do some caching.
  2. No, it's not. Check out gettext.


来源:https://stackoverflow.com/questions/7889181/php-function-for-language-translation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!