PHP: Set object properties inside a foreach loop

You can loop on an array containing properties names and values to set.

For instance, an object which has properties "$var1", "$var2", and "$var3", you can set them this way :

$propertiesToSet = array("var1" => "test value 1", 
                         "var2" => "test value 2", 
                         "var3" => "test value 3");
$myObject = new MyClass();
foreach($propertiesToSet as $property => $value) {
    // same as $myObject->var1 = "test value 1";
    $myObject->$property = $value;
}

Would this example help at all?

$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>$value) {
    $object->$prop = $object->$prop +1;
}
print_r($object);

This should output:

stdClass Object
(
    [prop1] => 2
    [prop2] => 3
)

Also, you can do

$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>&$value) {
    $value = $value + 1;
}
print_r($object);

Tags:

Php