What are the potential drawbacks of incorporating language selection logic in multiple places within a PHP script?
Potential drawbacks of incorporating language selection logic in multiple places within a PHP script include code duplication, maintenance difficulties, and increased chances of introducing errors or inconsistencies. To solve this issue, it is recommended to centralize language selection logic in a separate file or function and call this function whenever language selection is needed in the script.
// Centralize language selection logic in a separate function
function getTranslatedText($key, $lang) {
$translations = [
'hello' => [
'en' => 'Hello',
'fr' => 'Bonjour',
'es' => 'Hola'
],
// Add more translations as needed
];
return $translations[$key][$lang] ?? $key;
}
// Example usage
$lang = 'en';
echo getTranslatedText('hello', $lang);