dongshen9686 2011-10-25 12:21
浏览 55
已采纳

用于语言翻译的php函数

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?

  • 写回答

3条回答 默认 最新

  • duanhuan7750 2011-10-25 12:41
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来