Dynamic properties name in PHP

偶尔善良 提交于 2021-02-17 06:19:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!