I'm building a multilingual site, and would like to store the language phrases in database.
This is my language table:
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
field stores the phrase
key, while the value
is the actual pharase
The function below is part of 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;
}
I would like to be able to call language phrase like:
Language::HELLO
, which would print "Hello"
in the above HELLO
is the key, while Hello
is the phrase needs to be printed.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.