My php multilanguage class returns translated text by field when i call the class. I use echo for return translated text because i fetch whole page in class and translate them in foreach. Problem is when i return translated text with echo, $lang->Translate("PLANT") it jumps outside where i put it. How can i solve this issue. (By the way i can't use just return it only returns 1 row of language table)
The Language Table
echo '
<div >
<table >
<thead >
<tr>
<th scope="col"></th>
<th scope="col"><b></b></th>
<th scope="col"><b>'.$lang->Translate("PLANT").'</b></th>
<th scope="col" ><b>'.$lang->Translate("COMPANY").'</b></th>
<th scope="col" ><b></b></th>
<th scope="col" ><b></b></th>
<th scope="col" ><b></b></th>
<th scope="col" ><b></b></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
';
my language class
class Lang {
public function Language()
{
static $table = array();
static $loaded = false;
if (!$loaded) {
$loaded = true;
$lang = strtoupper(substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2));
include("settings.php"); //DB Connection
$sql = $MYSQLdb->prepare("SELECT * FROM language");
$sql->execute();
while($print = $sql->fetch(PDO::FETCH_ASSOC))
{
$field = array($print["FIELD"] => $print[$lang]);
array_push($table, $field);
}
return $table;
} else {
return $table;
}
}
public function Translate($translate)
{
$table = $this->Language();
foreach($table as $fields) {
echo $fields[$translate];
}
}
}
$lang = new Lang();
CodePudding user response:
As when you do this
$field = array($print["FIELD"] => $print[$lang]);
you are making an array of word,translation i.e.
COMPANY ENTERPRISE
PLANT PLANTE
I see no reason why you cannot return
the translation from this method I would change the method slightly as there seems to be no reason for a loop.
public function Translate($translate)
{
$table = $this->Language();
return $table[$translate];
}
Or even like this so you dont need to make a copy of the array
public function Translate($translate)
{
return $this->Language()[$translate];
}
CodePudding user response:
I could go into further improvements to your class but I will focus on your particular issue.
In short change echo to return and the output will be included in your table markup:
public function Translate($translate)
{
$table = $this->Language();
foreach($table as $fields) {
return $fields[$translate];
}
}
Now that is only going to work if that function always returns 1 word because it is going to exit your foreach loop. If the foreach is not neccessary then do this instead (as now mentioned by @RiggsFolly):
public function Translate($translate)
{
$table = $this->Language();
return $table[$translate];
}