How to define a function for language terms in php
I have a function for language (like the system that Wordpress and other CMSes have) to retun a term in defined language as
function lang($term) {
include "language/cn.php";
if(!empty($tans[$term])) {$translatedterm=$tans[$term];}
else { $translated = $term;}
return $translated;
}
The problem is that I want to offer the option of choosing language on menu, as people can change the language. To this aim, I need to update the value of "include 'language/cn.php'" for every language. It should be inc开发者_Python百科lude "language/$language.php";
but $language
is a string coming from menu selection and is outside the function. Do you have any idea how to change the language file inside the function depending on the language selected?
In the code that processes the language selection form, you can store the chosen language in the session:
$allowed_languages = array('en', ...);
if (array_key_exists($_POST['language'], $allowed_languages)) {
$_SESSION['language'] = $_POST['language'];
}
Then, in this function, pull the language from the session if it's available:
function lang($term) {
$language = isset($_SESSION['language']) ? $_SESSION['language'] : 'en';
require_once 'language/' . $langauge . '.php';
// ...
}
You're doing this:
include 'language/$language.php';
This won't work because PHP only interprets variables inside a string when the string is double-quoted. As you've got it there, it will simply take the string as you've specified it, without converting the variable name.
You can either take the variable outside the string like so:
include 'language/' . $language.php;
or use double-quotes for your string, like so:
include "language/{$language}.php";
(the curly braces around the variable name are optional in this context, but recommended)
Both of these will result in $language
being converted to the required value before the file is included.
Hope that helps.
According to the hint given by Alex Howansky, the ultimate solution is to use a php variable like $_SEESION, $_GET, $_POST, etc. These variable can be used within a function. However, as a function has its own scope, a static string from outside a function cannot be read inside the function.
are you going to include translations file for the EVERY term?
load your translations file once and safe:
function lang($term) {
static $trans;
if (!$trans) {
global $language; // seems the problem as silly as this
$langfile = "language/".basename($language).".php";
if (!is_readable($langfile)) {
$langfile = "language/default.php";
}
include $langfile;
}
return (empty($trans[$term]))?$term:$trans[$term];
}
精彩评论