PHP中的动态属性名称 [英] Dynamic properties name in PHP

查看:47
本文介绍了PHP中的动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中有一个名为 $ item 的对象,在该对象中,我具有

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(); ?>

函数:

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

但是,名称生成不正确,只是$ item-> title附加了语言代码的字符串,例如我的标题1234_tw,titleABC_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

推荐答案

您应该首先将 $ item-> title 连接到 set_lang()上,然后将其放置在变量.

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

然后可以使用该变量在obj上调用right属性.

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

示例

$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 ;)

这篇关于PHP中的动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆