php - 从MySQL检索语言短语

时间:2014-03-11 20:15:52

标签: php mysql multilingual

我正在建立一个多语言网站,并希望将语言短语存储在数据库中。

这是我的语言表:

CREATE TABLE `language` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key` varchar(100) DEFAULT NULL,
  `value` varchar(150) DEFAULT NULL,
  `type` varchar(50) DEFAULT NULL,
  `abr` varchar(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

key字段存储phrase密钥,而value是实际的短语

以下函数是Language class:

的一部分
public static function getPhrases()
{   
    $sql  = "SELECT * FROM language ORDER BY type";
    $data = $db->fetch($sql);

    $vals = array();
    foreach($data as $k => $row) 
    {
        $vals[] = $row->key;
    }

    return $vals;
}

我希望能够像以下一样调用语言短语:

Language::HELLO,打印" Hello"

上面HELLO中的

是关键,而Hello是需要打印的短语。

1 个答案:

答案 0 :(得分:0)

class Language {

    private $phrases;

    public function __construct($phrases = array()){
        $this->phrases = $phrases;
    }


    /**
    * Dynamically create getters for phrases
    * @param $name string
    */
    public function __get($name) {
        if (array_key_exists($name, $this->phrases)) {
            return $this->phrases[key];
        }
    }

    /**
    * Load language from database
    */
    public static function getLangauge(){   
        $sql  = "SELECT * FROM language ORDER BY type";
        $data = $db->fetch($sql);

        $vals = array();
        foreach($data as $k => $row) 
        {
            $vals[] = $row->key;
        }

        return new self($vals);
    }

}

$foolang = new Language(array('foo' => 'bar'));
echo $foolang->foo;
// bar