问题
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
回答1:
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 ;)
来源:https://stackoverflow.com/questions/30254707/dynamic-properties-name-in-php