💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 14. 插件多语言 ## 多语言 插件多语言仅用于插件内的访问 ## 创建语言包 在你的插件根目录下创建`lang`名字的文件夹,该文件夹里面放语言包即可,路径为:addons/demo/lang/。如下图所示 ![](https://img.kancloud.cn/38/b2/38b2eef5d37ffd46b0d23755a35ad9e6_332x262.png) 其中里面还创建了`zh-cn`文件夹,该文件夹里的语言包不是全局的,作用范围仅限控制器,跟控制器名保持一致,小写命名。如上图`index.php`语言包仅作用于`Index`控制器 ## 多语言的使用 使用`lang`函数即可调用 ``` <pre class="calibre16">``` <span class="token5">/** * $name 语言变量名 * array $vars 动态变量值 * $lang 指定语言 */</span> <span class="token6">lang</span><span class="token1">(</span>string $name<span class="token1">,</span> array $vars <span class="token">=</span> <span class="token1">[</span><span class="token1">]</span><span class="token1">,</span> string $lang <span class="token">=</span> <span class="token4">''</span><span class="token1">)</span> ``` ``` zh-cn 语言包 ``` <pre class="calibre16">``` <span class="token"><</span><span class="token">?</span>php <span class="token2">return</span> <span class="token1">[</span> <span class="token4">'Demo'</span> <span class="token">=</span><span class="token">></span> <span class="token4">'演示'</span> <span class="token1">]</span><span class="token1">;</span> ``` ``` Index控制器使用 ``` <pre class="calibre16">``` <span class="token"><</span><span class="token">?</span>php namespace addons\demo\controller<span class="token1">;</span> use think\addons\Controller<span class="token1">;</span> class <span class="token6">Index</span> extends <span class="token6">Controller</span> <span class="token1">{</span> public <span class="token2">function</span> <span class="token6">index</span><span class="token1">(</span><span class="token1">)</span> <span class="token1">{</span> echo <span class="token6">lang</span><span class="token1">(</span><span class="token4">'Demo'</span><span class="token1">)</span><span class="token1">;</span> <span class="token5">// 当语言切换到zh-cn时会输出演示,如果没有匹配到就输出Demo</span> <span class="token1">}</span> <span class="token1">}</span> ``` ``` - 动态变量值 当我们需要里面某些值需要动态化时即可使用参数2传入,如下 ``` <pre class="calibre16">``` <span class="token"><</span><span class="token">?</span>php <span class="token2">return</span> <span class="token1">[</span> <span class="token4">'Hello, %s!'</span><span class="token">=</span><span class="token">></span><span class="token4">'您好,%s!'</span> <span class="token1">]</span><span class="token1">;</span> ``` ``` ``` <pre class="calibre20">``` public <span class="token2">function</span> <span class="token6">index</span><span class="token1">(</span><span class="token1">)</span> <span class="token1">{</span> <span class="token5">// 中文结果,您好,admin!支持多个%s占位符。</span> echo <span class="token6">lang</span><span class="token1">(</span><span class="token4">'Hello, %s!'</span><span class="token1">,</span><span class="token1">[</span><span class="token4">'admin'</span><span class="token1">]</span><span class="token1">)</span><span class="token1">;</span> <span class="token1">}</span> ``` ```