php function for language translation

妖精的绣舞 提交于 2019-12-04 15:44:31

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() ;)

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

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

  1. IIRC, it will do some caching.
  2. No, it's not. Check out gettext.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!