修改 PHP 对象属性名称

发布于 2024-11-09 12:34:33 字数 390 浏览 0 评论 0原文

在 PHP 中是否可以更改对象属性键/名称?例如:

stdClass Object
(
     [cpus] => 2
     [created_at] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

我希望将对象中的键 created_at 更改为 created ,留下一个如下所示的对象:

stdClass Object
(
     [cpus] => 2
     [created] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

In PHP is it possible to change an Objects property key/name? For example:

stdClass Object
(
     [cpus] => 2
     [created_at] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

I wish to change the key created_at to created in the Object leaving an object that looks like:

stdClass Object
(
     [cpus] => 2
     [created] => 2011-05-23T01:28:29-07:00
     [memory] => 256
)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

新一帅帅 2024-11-16 12:34:33
$object->created = $object->created_at;
unset($object->created_at);

不过,适配器类之类的东西可能是更可靠的选择,具体取决于需要执行此操作的位置和频率。

class PC {
    public $cpus;
    public $created;
    public $memory;

    public function __construct($obj) {
        $this->cpus    = $obj->cpu;
        $this->created = $obj->created_at;
        $this->memory  = $obj->memory;
    }
}

$object = new PC($object);
$object->created = $object->created_at;
unset($object->created_at);

Something like an adapter class may be a more robust choice though, depending on where and how often this operation is necessary.

class PC {
    public $cpus;
    public $created;
    public $memory;

    public function __construct($obj) {
        $this->cpus    = $obj->cpu;
        $this->created = $obj->created_at;
        $this->memory  = $obj->memory;
    }
}

$object = new PC($object);
纸短情长 2024-11-16 12:34:33

不,因为键是对值的引用,而不是值本身。
您最好复制原件,然后将其删除。

$obj->created = $obj->created_at;
unset(obj->created_at);

No, since the key is a reference to the value, and not a value itself.
You're best off copying the original, then removing it.

$obj->created = $obj->created_at;
unset(obj->created_at);
空城仅有旧梦在 2024-11-16 12:34:33

它类似于 @deceze 适配器,但不需要创建额外的类

$object = (object) array(
  'cpus'    => $obj->cpus,
  'created' => $obj->created_at,
  'memory'  => $obj->memory
);

Its similar to @deceze adapter, but without the need to create an extra class

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