There is a session variable called 'locale' with value: en.
$locale = session()->get('locale'); // value = 'en';
And there is an object $page
with attributes: content_en
, content_ru
, content_de
.
All I need is to echo $page->content_en
or $page->content_ru
or $page->content_de
, but depending on locale.
echo $page->content_'.session()->get('locale').';
Fabian's answer is more flexible and generally better. However, here's an alternative approach if you only accept specific values.
if
$locale = session()->get('locale'); // value = 'en';
if ($locale == "en") {
echo $page->content_en;
} elseif ($locale == "ru") {
echo $page->content_ru;
} elseif ($locale == "de") {
echo $page->content_de;
}
switch
$locale = session()->get('locale'); // value = 'en';
switch ($locale) {
case "en":
echo $page->content_en;
break;
case "ru":
echo $page->content_ru;
break;
case "de":
echo $page->content_de;
break;
}
Here's a more complete solution that you can even run on phpfiddle.org
$page = new stdClass();
$page->content_en = 'Testcontent';
$page->content_de = 'Testinhalt';
$property = 'content_' . locale("en");
if(property_exists($page, $property)) {
// The property exists, print it!
echo $page->$property;
} else {
// Fallback to some default
}
function locale($loc)
{
return $loc;
}
You won't be able to access a property via a combined string. The only option you have is to first put it in a string, and use that variable as a property access.
$property = 'content_' . session()->get('locale');
if( isset($page->$property) ) {
echo $page->$property;
}
This should do it:
echo $page->{'content_' . session()->get('locale')};