html - Dynamic properties name in PHP -
there object in php named $item
, , in object have properties of
title , title_cn, title_tw
and create function auto generate properties based on language, coding this:
<?= $item->title . set_lang(); ?>
and 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, name not generated correctly, $item->title append string of lang code, e.g. my title 1234_tw, titleabc_cn
etc...
how dynamic generate properties ? fo helping
you should first concatenate $item->title
onto set_lang()
, place in variable.
you can use variable call right property on obj.
example
$itemlangtitle = $item->title . set_lang(); echo $item->$itemlangtitle
you can use variables properties dynamically careful user input always!
on sidenote need make sure property exists otherwise you'll errors. make sure if doesn't yield should fallback english naming or unobstructive ;)
Comments
Post a Comment