0

There is an object in PHP named $item , and in this object I have properties of

title , title_cn, title_tw

And I would like to create an function that auto generate the properties based on the language, so I coding like this:

<?= $item->title . set_lang(); ?>

And the function:

function set_lang() {
    $CI =& get_instance();
    $lang = $CI->session->userdata('site_lang');
    if ($lang == "english") {
        return "";
    } else if ($lang == "zh_tw") {
        return "_tw";
    } else if ($lang == "zh_cn") {
        return "_cn";
    }
}

However, the name is not generated correctly, it is just the $item->title append with the string of lang code, e.g. my title 1234_tw, titleABC_cn etc...

How to dynamic generate the properties ? Thanks fo helping

2
  • 1
    Search for variable variables Commented May 15, 2015 at 8:20
  • Var vars are easy to understand once you get them ;P But they are not needed in this case unless you want to shorten the code making it more difficult to understand ;) Commented May 15, 2015 at 8:26

1 Answer 1

2

You should first concatenate $item->title onto set_lang() and place that in a variable.

You can then use that variable to call the right property on the obj.

example

$itemLangTitle = $item->title . set_lang();

echo $item->$itemLangTitle

You can use variables as properties dynamically but be careful with user input as always!

On a sidenote you also need to make sure the property exists otherwise you'll get errors. So make sure that if this doesn't yield anything it should fallback to english naming or something unobstructive ;)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.