2010-11-07 37 views
1

在很多平台上很常见,而不是直接在代码中嵌入字符串,制作资源表或字符串表,其中列出所有消息,代码引用它们。这使翻译应用程序变得很容易,或让非开发人员更改消息措辞。PHP:使用字符串表/资源表来改变品牌和i18n

什么是在PHP中这样做的建议方式?有没有好的,简单的标准解决方案,还是它是你自己的角色?一个简单的表格很容易 - 我担心的是,我已经使用PHP,HTML和JavaScript的PHP文件在一起,并且知道你在哪里并不总是容易...

回答

0

i18n/l10n字典是简单的关联数组(键值对),可以使用常规PHP代码,.ini文件或数据库表(甚至NoSQL)来完成。如果字典不是那么大,你最好的选择就是PHP文件。如果用户群是非编码器,请考虑.ini文件。如果您预见字典短语会随着时间而增长(并且可能不适合可用的PHP内存),那么数据库选项是最佳选择。拿你的选择。

0

我以前用一个完整的define()d字符串的简单PHP文件完成了这项工作。

(english.php)

<?php 
define ('MSG_OK_LOGIN', 'You have successfully logged in. Welcome back'); 
define ('MSG_ERR_LOGIN', 'Unable to log you in. ') 
define ('MSG_ERR_LOGIN_USERNAME', MSG_ERR_LOGIN . 'Please register before attempting to log in'); 
define ('MSG_ERR_LOGIN_PASSWORD', MSG_ERR_LOGIN . 'Please check that you have typed your password correctly, and that your caps lock key is off. '); 
// ... 
?> 

然后在您的登录页面,

<?php 
require ('path/to/your/config.php'); // A configuration for the software. Assume it contains a define ('CFG_LANG', 'english'); line in it somewhere 
require ('path/to/language/files/' . CFG_LANG . '.php'); 
// ... 
?> 
+0

看起来像戈登有一个风扇,HTTP:// stackoverflow.com/users/208809/gordon – RobertPitt 2010-11-07 22:37:04

3

个人而言,我不会使用定义的,由Gordon说,但我会做一些像这样:

class Language 
{ 
    var $language; 
    var $storage = array(); 

    public function __construct($language) 
    { 
     $this->language = $language; 
     $this->load(); 
    } 

    private function load() 
    { 
     $location = '/path/to/' . $this->language . '.php'; 

     if(file_exists($location)) 
     { 
      require_once $location; 
      if(isset($lang)) 
      { 
       $this->storage = (object)$lang; 
       unset($lang); 
      } 
     } 
    } 

    public function __get($root) 
    { 
     return isset($this->storage[$root]) ? $this->storage[$root] : null; 
    } 
} 

因此,上述将是一个非常基本的语言对象,语言文件会像这样:

/path/to/english.php

$lang = array(
    'user' => array(
     'welcome' => 'Welcome %s', 
     'logout' => 'Logout', 
    ) 
    /*...*/ 
); 

你应该有多个文件进行各种语言环境,但这样,如果密钥不中German存在,那么你应该修改你的类它应该默认为英文本地,因为这是主要的

所以用法就是这样。

$lang = 'english'; //logic behind this to detect the browser or user data. 

$Language = new Language($lang); 

echo sprintf($Language->user->welcome,"RobertPitt"); // Welcome RobertPitt 
+0

我试过用这个,我似乎无法交流通过使用语法“$ Language-> user-> welcome”来停止。 我刚刚得到这个错误消息:“致命错误:不能使用stdClass类型的对象作为数组在34行/var/www/html/workspace/srclistv2/Resource.php” (我叫我的类资源,不是语言)。 – Twistar 2012-11-22 09:33:59

+0

你确定不是:'$ this-> storage - > $ root'而不是'$ this-> storage [$ root]'?...毕竟是一个对象... – HellBaby 2015-03-23 11:25:38