Current Location: Home> Latest Articles> Complete Guide to Implementing Chinese-English Language Switching in ThinkPHP

Complete Guide to Implementing Chinese-English Language Switching in ThinkPHP

gitbox 2025-07-28

Introduction

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.

Installing ThinkPHP

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.

Configuring Language Support

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.

Creating Language Files

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.

Switching Languages in Controllers

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.

Displaying Translations in Templates

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.

Detecting Current Language in Templates

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.

Conclusion

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.