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 class="table-responsive"> <table class="table table-striped table-hover"> <thead class="thead-light"> <tr> <th scope="col"></th> <th scope="col"><b></b></th> <th scope="col"><b>'.$lang->Translate("PLANT").'</b></th> <th scope="col" class="d-none d-sm-table-cell"><b>'.$lang->Translate("COMPANY").'</b></th> <th scope="col" class="d-none d-sm-table-cell"><b></b></th> <th scope="col" class="d-none d-sm-table-cell"><b></b></th> <th scope="col" class="d-none d-sm-table-cell"><b></b></th> <th scope="col" class="d-none d-sm-table-cell"><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();
Advertisement
Answer
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]; }