olanod olanod - 2 months ago 5
PHP Question

PHP Object, set multiple properties

Is it possible to set multiple properties at a time for an object in php?
Instead of doing:

$object->prop1 = $something;
$object->prop2 = $otherthing;
$object->prop3 = $morethings;


do something like:

$object = (object) array(
'prop1' => $something,
'prop2' => $otherthing,
'prop3' => $morethings
);


but without overwriting the object.

Answer

Not like the way you want. but this can be done by using a loop.

$map =  array(
    'prop1' => $something,
    'prop2' => $otherthing,
    'prop3' => $morethings
);

foreach($map as $k => $v)
    $object->$k = $v;

See only 2 extra lines.

Comments