When building multilingual web applications, supporting Chinese and English switching is a common requirement. This article focuses on the ThinkPHP framework and explains how to implement flexible language switching functionality to improve the international user experience.
Start by installing ThinkPHP version 6 via Composer. Use the following command to quickly set up your development environment:
composer create-project topthink/think myproject 6.0.*
Once installed, you can begin configuring the language switching feature.
Add language-related settings to your project’s configuration file, usually located at config/app.php:
// config/app.php
return [
// Default language
'default_lang' => 'zh-cn',
// Supported language list
'lang_list' => ['zh-cn', 'en-us'],
];
This setup defines Chinese as the default language and lists both Chinese and English as supported languages.
In the app/lang directory, create two language files: zh-cn.php and en-us.php, which contain the translations:
// app/lang/zh-cn.php
return [
'hello' => '你好',
'welcome' => '欢迎来到我的网站',
];
// app/lang/en-us.php
return [
'hello' => 'Hello',
'welcome' => 'Welcome to my website',
];
Each file defines the same language keys with respective Chinese or English values.
You can switch the language in a controller by setting a cookie value:
public function switchLanguage($lang)
{
if (in_array($lang, config('lang_list'))) {
cookie('think_var', $lang);
}
}
This function sets a cookie for the language preference if the provided language is in the supported list.
Use the lang() function in templates to retrieve translation values:
echo lang('hello');
This function will return the correct text based on the currently selected language.
To show the current language in the interface, you can check the language cookie in your template:
echo cookie('think_var') === 'en-us' ? ' English' : ' 中文';
This helps dynamically indicate the current language to the user.
By configuring supported languages, creating language files, and managing language preferences via cookies, developers can easily implement Chinese-English language switching in ThinkPHP. This approach is flexible and efficient, making it suitable for any web project that requires internationalization support.