首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 中英語言切換類:文字檔儲存、單例、按需載入

     編輯:PHP 綜合知識

設計目標

  • 翻譯對照存於純文字檔(unit.txt、menu.txt...),易維護。
  • 單例模式,按類型($type)載入對應檔案,避免一次載入所有翻譯。
  • 支援 Cookie/GET/POST 切換語系,預設中文。

文字檔格式

# unit.txt
hello 你好
min 分鐘
minute 分鐘
minutes 分鐘

核心類

class Language {
    static $instance;
    public $type; // 當前載入的檔案類型
    public $lang; // 當前語系:zh/en/all
    private $dict; // 當前字典內容

    private function __construct() {
        $hl = $_GET['hl'] ?? $_POST['hl'] ?? $_COOKIE['hl'] ?? 'zh';
        $this->lang = in_array($hl, ['en','zh','all']) ? $hl : 'zh';
    }

    public static function getObject() {
        if (!(self::$instance instanceof self)) self::$instance = new self();
        return self::$instance;
    }

    // 輸出翻譯(若非中文直接回傳鍵值)
    public function lto($key) {
        if ($this->lang !== 'zh') return $key;
        if (empty($this->dict)) {
            if ($this->type) $this->dict = file_get_contents($this->type . '.txt');
            else return $key;
        }
        echo $this->search($key);
    }

    private function search($key) {
        $start = strpos($this->dict, $key);
        if ($start === false) return $key;
        $start += strlen($key) + 1; // 跳過鍵值與空白
        $end = strpos($this->dict, ' ', $start);
        if ($end === false) $end = strlen($this->dict);
        return substr($this->dict, $start, $end - $start);
    }
}

使用範例

$L = Language::getObject();
$L->type = 'unit';
$L->lto('minute'); // 輸出:分鐘
$L->lto('hello');  // 輸出:你好

優缺點

  • 優點:無資料庫依賴、檔案可由非技術人員編輯、按需載入節省記憶體。
  • 缺點:大量翻譯時檔案搜尋效能較差(建議改用 PHP 陣列檔或快取)。
  • 擴充:可加入 Accept-Language 自動偵測、支援複數形式、變數插值。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved