0

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').';

4 Answers 4

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

It does, but has not been requested. If it's needed, I'll add it
I suggest you add it to your answer. Some people might not recognize that this is required.
Thank you so much!
0

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;
}

Comments

0

Fabian's answer is more flexible and generally better. However, here's an alternative approach if you only accept specific values.

Using 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;
}

Using 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;
}

2 Comments

And this approach will only work for property names known at the time of implementation. Not for dynamically created objects.
@arkascha Correct. Fabians answer is better for that purpose. This is just an alternative approach.
0

This should do it:

echo $page->{'content_' . session()->get('locale')};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.