在 PHP 中使用字符串属性名称设置对象的属性
我希望能够设置对象的属性,但会生成属性名称。如何在 PHP 中完成此操作,而不使用 eval()
例如:
$obj->name = "Prakash Raman"; // Works
$obj->$attr_name = <some value>; // Would want something like this to work
我希望能够更改 $attr_name
。
谢谢。
I want to be able to set an attribute of an object but the attribute name would be generated. How can I accomplish this in PHP, without using eval()
e.g.:
$obj->name = "Prakash Raman"; // Works
$obj->$attr_name = <some value>; // Would want something like this to work
I would like to be able to change $attr_name
.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将完全实现这一点。
不过,请注意,我建议将其与
property_exists()
结合使用 验证该属性是否存在。This will accomplish exactly that.
A word of caution though, I would reccomend using it in conjunction with
property_exists()
to verify the existence of the property.我知道这个问题有一个有效的答案,但只是添加了许多可以做到这一点的方法:
I understand the question has a valid answer, but just to add onto the many ways you can do this:
有趣的是,您发布的代码将起作用。 (++ 对于 property_exists,不过。)
http://codepad.org/qW0Tj4MR
Funnily enough, your code as posted will work. (++ for property_exists, though.)
http://codepad.org/qW0Tj4MR