在PHP中,是否可以更改Objects属性键/名称?例如:
stdClass Object
(
[cpus] => 2
[created_at] => 2011-05-23T01:28:29-07:00
[memory] => 256
)
我希望将Object中的关键字created_at
更改为created
,留下一个看起来像的对象
stdClass Object
(
[cpus] => 2
[created] => 2011-05-23T01:28:29-07:00
[memory] => 256
)
$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);
否,因为键是对值的引用,而不是值本身。你最好复制原件,然后把它删除。
$obj->created = $obj->created_at;
unset(obj->created_at);
它类似于@deceze适配器,但不需要创建额外的类
$object = (object) array(
'cpus' => $obj->cpus,
'created' => $obj->created_at,
'memory' => $obj->memory
);