Grazie mt19.
Si potrebbe fare anche una classe così:
- langs/
- it_IT.json
codice:{ "hello" => "hello", /* ... ... ... ... */ }- es_ES.json
codice:{ "hello" => "hola", /* ... ... ... ... */ }- classes/
- Translator.class.php
Codice PHP:
class Translator {
private static $folder = "langs";
private $translator = array();
private $lang = "";
public static function setFolder($new_folder) {
if (is_dir($folder)) self::$folder = $new_folder;
}
public function __construct ($lang) {
$info = array();
if (!preg_match("/^(?<language>[a-z]{2})(_(?<locality>[A-Z]{2}))?$/", $lang, $info))
throw new Exception;
$this->lang = $lang;
$dir = dir(self::$folder);
$files = array();
while (($file = $dir->read()) !== false) {
if (!in_array($file, [".", ".."]) && preg_match("/.*?\.json/", $file)) $files[] = $file;
}
$dir->close();
if (in_array($lang . ".json", $files)) {
$this->translator = (array) json_decode(file_get_contents(self::$folder . "/$lang.json"));
}
else {
$founded = false;
foreach ($files as $file) {
if (strpos($file, $info["language"]) === 0) {
$this->translator = (array) json_decode(file_get_contents(self::$folder . "/$file"));
$founded = true;
break;
}
}
if (!$founded) throw new Exception;
}
}
public function __get ($word) {
if (isset($this->translator[$word])) return $this->translator[$word]; return $word;
}
public function translateFrom ($word, $from) {
$from = $from instanceof self ? $from : new self($from);
return $from->translateTo($word, $this);
}
public function translateTo ($word, $to) {
$to = $to instanceof self ? $to : new self($to);
return in_array($word, $this->translator) ? $to->{array_search($word, $this->translator)} : $word;
}
}
- index.php
Codice PHP:
require_once ("classes/Translator.class.php");
$es = new Translator("es_ES"); // Creo il traduttore per la lingua spagnola
echo $es->hello; // Stampa "hola"
echo "<br>";
echo $es->translateTo("hola", "it_CH"); // Stampa "ciao". Non esistendo il file it_CH.json (Svizzera) la classe va a cercare il primo file che trova che sia it_**.json (L'italiano parlato in un altro stato, ad esempio it_IT)