PHP对象:通过计算名字来取得属性的值 [英] php object : get value of attribute by computed name

查看:140
本文介绍了PHP对象:通过计算名字来取得属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过名称访问对象的属性,如果我在运行时计算的名字吗?

How do I access an attribute of an object by name, if I compute the name at runtime?

有关实例。我遍历键,并希望得到的属性field_的每个​​值。 $键

For instance. I loop over keys and want to get each value of the attributes "field_" . $key.

在蟒蛇有的getAttribute(为MyObject,attrname)

它的工作原理,当然与的eval($ VAL = $ myobject->中$ myattr。;);
但IMO这是丑陋的 - 有一个更清洁的方式来做到这一点。

It works, of course, with eval("$val=$myobject->".$myattr.";"); but IMO this is ugly - is there a cleaner way to do it?

推荐答案

始终记住,PHP的一个非常强大的功能是它的可变变量

Keep always in mind that a very powerful feature of PHP is its Variable Variables

您可以使用

$attr = 'field' . $key;
$myobject->$attr;

或更简洁,使用curl括号

or more concisely, using curl brackets

$myobject->{'field_'.$key};

这篇关于PHP对象:通过计算名字来取得属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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