15

In PHP is it possible to change an Objects property key/name? For 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
)

3 Answers 3

21
$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);
Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

The "No" should be actually a "Yes"! You give the wrong answer, but provide the right solution.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.