duanfei1987 2011-09-11 13:46
浏览 27

优化国际化脚本,我做出了不错的选择吗?

I'm going ahead to develop the localization files for my project and i am not sure if i am doing the good choice.

<?php
$translation= array(
    "sentence" => array ("fr" => "phrase", "it" => "frase")
);

function _($toTranslate = '', $lang = 'en'){

    if($toTranslate != ''){

        if(!array_key_exists($toTranslate[$lang], $translation))
            return $toTranslate;

        else 
            return ${$lang}[$toTranslate];
    }
}
?>

I clearly no idea to know if i am doing it well.

  • 写回答

1条回答 默认 最新

  • dongqin8652 2011-09-11 14:00
    关注

    Not good enough.

    1. Improvement to your implementation.

    Place each language in an single file would be better for performance and maintenance. For example, make a folder called "language", it contains "fr.inc.php", "de.inc.php" and so on. In the config file, you have a line like

    $config['language'] = 'de';
    

    You can also load the language code from GET parameter:

    $config['language'] = htmlspecialchars($_GET['lang']);
    

    Remember to have check if the language file exists or not (file_exists())

    In your bootstrap code, you load the language file (check it before)

    require_once LANGUANGE_DIR . '/' . $config['language'] . '.inc.php';
    

    and when you need the language resource string, you call your "_" function, now it should look like

    function _($LANG_RES_ID) {
        global $lang;
        return isset($lang[$LANG_RES_ID] ? $lang[$LANG_RES_ID] : $LANG_RES_ID;
    }
    

    2 Use gettext

    see php.net: http://www.php.net/gettext

    Also, many open source apps are good cases for study, phpMyAdmin, for example.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看