修改PHP对象属性名称

时间:2011-05-24 08:48:17

标签: php object properties

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

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
)

3 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:0)

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

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