我有一个小问题:
让我们说:我有一个脚本翻译我的网站。大致是这样的:
//getting browser language
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($lang !== 'pt'){
$lang == 'en';
}
,我包含了几个php文件中的一个,其中有翻译数组:
$path = 'languages/';
include_once($path.$lang.'.php');
翻译数组示例:
//pt.php
$translate = array(
'Hello' => 'Olá',
'World' => 'mundo'
);
现在的主要思想是有一个word类让这个数组翻译字符串并把第一个字母变成大写。所以我现在得到的是:
//类word.php
class word {
public function translate($lang, $string){
global $translate;
include('languages/'.$lang.'.php');
$string = $translate['hello'];
return $string;
}
function uc_sentence($string){
$string = ucfirst(strtolower($string));
$string = preg_replace_callback('/[.!?].*?'w/', create_function('$matches', 'return strtoupper($matches[0]);'),$string);
echo $string;
}
}
那么,这里发生了什么?我可以这样做:
$word = new word();
$word->translate('pt',$string);
$word->uc_sentence($string);
它将输出翻译后的字符串。但在我看来,这就像一个非常糟糕的编码。
我想到的是使include_once('pt.php')对类中的所有函数可用,然后在uc_sentence中运行翻译。
传递数组作为word
构造函数的参数:
class word {
private $words;
public function __construct(array $words) {
$this->words = $words;
}
// rest of class here
}
// When translating:
$word = new word($translate);
$word->translate('fr', $string);
这个概念被称为依赖注入,但是如果你有更多的数组要传递,我会这样做:
class word {
private $words = array();
public function __construct(array $words) {
$this->addWords($words);
}
public function addWords(array $words) {
$this->words = array_merge($this->words, $words);
}
// rest of class here
}