开发者

Modify PHP Object Property Name

开发者 https://www.devze.com 2023-03-08 04:07 出处:网络
In PHP is it possible to change an Objects property key/name? Fo开发者_运维知识库r example: stdClass Object

In PHP is it possible to change an Objects property key/name? Fo开发者_运维知识库r 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
)


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消