Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify PHP Object Property Name

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
)
like image 457
Justin Avatar asked May 24 '11 08:05

Justin


People also ask

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

What is object properties PHP?

In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.

What is a stdClass object?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


2 Answers

$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);
like image 87
deceze Avatar answered Sep 19 '22 08:09

deceze


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);
like image 22
dkruythoff Avatar answered Sep 19 '22 08:09

dkruythoff