【问题标题】:switch or file_exists for locales语言环境的 switch 或 file_exists
【发布时间】:2018-10-18 18:17:28
【问题描述】:

我创建了一个多语言网站,我想知道如何获取语言数据。好吧,我的代码从浏览器获取有关用户语言的信息,然后包含语言环境文件。

获取用户语言:

<?php
$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
?>

包括语言环境:

<?php
if (file_exists('locales/".$hl.".php')){
  include "locales/".$hl.".php";
}else{
  include "locales/en.php";
}

/*    VS    */

switch ($hl){
  case 'de': include "locales/de.php"; break;
  case 'fr': include "locales/fr.php"; break;
  /* ...*/
  default: include "locales/en.php";
}
?>

哪种方式最好?

【问题讨论】:

  • 第一个会更短,有很多语言,我会用那个。
  • 您可能会在我的帖子中找到一些有用的信息。它从失败模式中检索语言:从 URL、会话、浏览器、回退。 stackoverflow.com/questions/49756515/…

标签: php


【解决方案1】:

有很多方法可以解决这个问题,这取决于我们在您的代码中不知道的许多事情。例如,locales/en.php 总是 是否可用(即不需要file_exists() 检查)。等等等等

即便如此,最好还是个人意见。

就个人而言,为了简洁但又不过分,我更喜欢:

$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
file_exists('locales/'.$hl.'.php')
    ? include 'locales/'.$hl.'.php'
    : include 'locales/en.php';

但这又取决于您,什么对您的要求和其他编码风格有意义。例如。如果重用已确定语言的值(例如“EN”或来自服务器变量的值,例如“DE”)有用,那么这会更好:

$hl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$language = file_exists('locales/'.$hl.'.php')
    ? $h1
    : 'en';
include 'locales/'.$language.'.php';

// $language can be used again, eg echo "currently viewing in {$language}";

你可以把它收紧,但要小心它不会变得不清楚。

$browserLanguageFile = 'locales/'.substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2).'.php';
file_exists($browserLanguageFile)
    ? include $browserLanguageFile
    : include 'locales/en.php';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    • 2013-01-10
    • 2020-04-05
    相关资源
    最近更新 更多