在 PHP 中使用字符串属性名称设置对象的属性

发布于 2024-12-26 11:07:28 字数 285 浏览 2 评论 0原文

我希望能够设置对象的属性,但会生成属性名称。如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心如狂蝶 2025-01-02 11:07:28
$obj->{$attr_name} = "New value";

这将完全实现这一点。

不过,请注意,我建议将其与 property_exists() 结合使用 验证该属性是否存在。

$obj->{$attr_name} = "New value";

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.

笔芯 2025-01-02 11:07:28

我知道这个问题有一个有效的答案,但只是添加了许多可以做到这一点的方法:

<?php
$myClass = new ReflectionClass($someClass);
if($myClass->hasProperty($someProperty)){
   $myClass->getProperty($someProperty)->setValue($someClass,__NEW__VALUE__);
}
?>

I understand the question has a valid answer, but just to add onto the many ways you can do this:

<?php
$myClass = new ReflectionClass($someClass);
if($myClass->hasProperty($someProperty)){
   $myClass->getProperty($someProperty)->setValue($someClass,__NEW__VALUE__);
}
?>
一笔一画续写前缘 2025-01-02 11:07:28

有趣的是,您发布的代码将起作用。 (++ 对于 property_exists,不过。)

http://codepad.org/qW0Tj4MR

Funnily enough, your code as posted will work. (++ for property_exists, though.)

http://codepad.org/qW0Tj4MR

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文