think\Lang::detect PHP Method

detect() public static method

自动侦测设置获取语言选择
public static detect ( ) : string
return string
    public static function detect()
    {
        // 自动侦测设置获取语言选择
        $langSet = '';
        if (isset($_GET[self::$langDetectVar])) {
            // url中设置了语言变量
            $langSet = strtolower($_GET[self::$langDetectVar]);
            Cookie::set(self::$langCookieVar, $langSet, self::$langCookieExpire);
        } elseif (Cookie::get(self::$langCookieVar)) {
            // 获取上次用户的选择
            $langSet = strtolower(Cookie::get(self::$langCookieVar));
        } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            // 自动侦测浏览器语言
            preg_match('/^([a-z\\d\\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
            $langSet = strtolower($matches[1]);
            Cookie::set(self::$langCookieVar, $langSet, self::$langCookieExpire);
        }
        if (empty(self::$allowLangList) || in_array($langSet, self::$allowLangList)) {
            // 合法的语言
            self::$range = $langSet ?: self::$range;
        }
        if ('zh-hans-cn' == self::$range) {
            self::$range = 'zh-cn';
        }
        return self::$range;
    }

Usage Example

Example #1
0
 public function testDetect()
 {
     Config::set('lang_list', ['zh-cn', 'zh-tw']);
     Lang::set('hello', '欢迎', 'zh-cn');
     Lang::set('hello', '歡迎', 'zh-tw');
     Config::set('lang_detect_var', 'lang');
     Config::set('lang_cookie_var', 'think_cookie');
     $_GET['lang'] = 'zh-tw';
     Lang::detect();
     $this->assertEquals('歡迎', Lang::get('hello'));
     $_GET['lang'] = 'zh-cn';
     Lang::detect();
     $this->assertEquals('欢迎', Lang::get('hello'));
 }
All Usage Examples Of think\Lang::detect