在 PHP 中实现多语言

Implementation of multilanguage in PHP

我想知道如何在 PHP 脚本中实现多种语言。我真的找不到任何方便的方法来说明如何做这样的事情以使翻译变得容易。我举个例子:

//Output looks like this:
//Where are You, Mike? It is me, Rebeca! I am waiting here for 5 hours!

//But in file it is some abomination like:
echo 'Where are You, '.$name.'? It is me, '.$name2.'! I am waiting here for '.$time.' hours!';

//Just imagine that meantime there might be different functions, included files
//and other code required to create more sentences like the above to create long text...

如果文件输出这样的文本被许多不同的变量和代码打碎,语言文件应该是什么样子?

我想到将用户语言保留在 $_SESSION['lang'] 中,并在每个文件中包含具有正确语言的文件。但是在我尝试这样做之后,它确实看起来像这样:

//main file
echo $txt[1].$name.$txt[2].$name2.$txt[3].$time.$txt[3];

//lang file
$txt[1] = 'Where are You, ';
$txt[2] = '? It is me, ';
$txt[3] = '! I am waiting here for ';
$txt[3] = ' hours!';

它看起来很可笑,不可读,而且有很多潜在的错误。试想一下,如果您是只能访问 lang 文件的翻译人员——不可能翻译这样的文本,对吧? should/could 如何以不同的方式完成?

是的,它是那样做的,但不是像你那样做的单个单词或句子块,否则翻译不好。

通常如何处理问题,定义模板,然后使用传递的参数调用函数。

请参阅:https://www.php.net/manual/en/refs.international.php 获取 gettext 等,或查找库。

示例:

<?php
$trans = [
    'en' => [
        'user_where_are_you_text' => 'Where are You, %s? It is me, %s! I am waiting here for %s hours!',
        //...
    ],
    'fr' => [
        'user_where_are_you_text' => 'Où es-tu, %s? C\'est moi, %s! J\'attends ici depuis %s heures!'
        //...
    ],
    //...
];

$name = 'Loz';
$name1 = 'Rasmus';
$time = 3;

function __($key, ...$arguments) {
    global $trans, $lang;
    return sprintf($trans[$lang][$key], ...$arguments);
}

//
$lang = 'en';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

//
$lang = 'fr';
echo __('user_where_are_you_text', $name, $name1, $time).PHP_EOL;

https://3v4l.org/e1nEB