我想创建一个多语言网站,但我有一个问题!
我将以一个例子向你解释:
的琅en.php
<?php
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
?>
的index.php
<?php
$useName = "Amir";
require_once("lang-en.php");
echo $lang['hello'];
?>
现在,我希望在我的页面中看到此输出:
欢迎Amir访问我们的网站!
我该怎么做?
答案 0 :(得分:3)
让它看起来更复杂,展望未来可能是明智之举。如果将实现部分删除到单独的类,则可以将实际用法和转换的实现分开。如果您打算稍后使用gettext
(po / mo文件),则可以更轻松地切换。
一个简单但未经测试的例子是
class translate{
private $translations = [
'hello' => "Wellcome %s to our website!",
]
public function trans($key, $value)
{
return sprintf($this->translations[$key], $value);
}
}
请注意,这是一个快速的例子,可能需要一些工作 - &gt;例如,它假定总是单个变量等等。但是这个想法是你创建一个带有内部实现的类,以及你调用的函数。如果您可以保持函数调用的足迹相同,则可以更改翻译系统的工作!
你会这样称呼
$trans = new Translate();
echo $trans->trans('hello', 'Amir');
(同样,我在答案框中输入了这个,没有检查语法,测试等已经完成,所以这可能不是一个复制粘贴就绪类,但它是关于这个想法)
编辑:根据要求,再多一点例子。再次,没有测试,可能是一些语法错误等,但帮助你的想法:
class translate{
private $translations = [
'hello' => array('test' =>"Welcome %s to our website!", 'vars' => 1),
'greet' => array('test' =>"I'd like to say $s to %s ", 'vars' => 2),
]
public function trans($key, array $values)
{
// no translation
if(!isset($this->translations[$key])){
return false; // or exception if you want
}
// translation needs more (or less) variables
if($this->translations[$key][vars] !== count($values)){
return false; // or exception if you want
}
// note: now using vsprintf
return vsprintf($this->translations[$key], $values);
}
}
答案 1 :(得分:0)
Amir Agha,
当您通过include
或require
调用另一个.php文件时,php的行为就好像所包含文件的内容插入同一行和相同的范围(类和函数除外)所以你在php解释器视图中的代码如下所示:
<?php
$userName = "Amir";
$lang = [];
$lang['hello'] = "Wellcome $userName to our website!";
echo $lang['hello'];
?>
所以这段代码必须显示:
Wellcome Amir访问我们的网站!
但为什么它不起作用?只是因为您在index.php文件中编写了$useName
而不是$userName
。
p.s。:其他答案使它非常复杂。仅将$useName
更改为$userName
答案 2 :(得分:0)
在lang-en.php中创建一个函数
<?php
function lang($username)
{
$lang['hello'] = $username;
echo $lang['hello'];
}
?>
在index.php中调用该函数
<?php
require_once("lang-en.php");
lang('arun');
?>
答案 3 :(得分:0)
<?php
//declare array
$lang = array();
$templang['hello1'] = "Wellcome ";
$templang['hello2'] = " to our website!";
//add new item in array
array_push($lang,$templang);
?>
的index.php
<?php
$useName = "Amir";
require_once("langen.php");
//it is first entry of array row so [0] is 0
echo $lang[0]['hello1'];
echo $userName;
echo $lang[0]['hello2'];
//out is welcome amir to our website
?>
这也是一个简单的方法,看看如何传递变量有点长的路,但我不想结合,以便你可以看到它是如何工作的,你也可以做一些关于在页面之间传递变量的会话的阅读不包括在内