在 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
)
最佳答案
$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);
关于php - 修改 PHP 对象属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107891/