2011-05-24 227 views
12

在PHP中可以更改對象屬性鍵/名稱?例如:修改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 
) 

回答

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

不,因爲鍵是對值的引用,而不是值本身。 您最好複製原稿,然後將其刪除。

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

它類似於@deceze適配器,但無需創建一個額外的類

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