Reputation: 80
Is it possible to set property values of an object using a foreach loop?
I mean something equivalent to:
foreach($array as $key=>$value) {
$array[$key] = get_new_value();
}
EDIT: My example code did nothing, as @YonatanNir and @gandra404 pointed out, so I changed it a little bit so it reflects what I meant
Upvotes: 5
Views: 8692
Reputation: 1
I suggest the function for set all properties of object by properties from another object.
//from object "from" all values will be set into object $to
function setAllProperties(object $from, object $to)
{
$map = (array) ($from);
foreach ($map as $key => $value) {
$position = mb_strrpos($key, "\x00");
$propertyName = substr($key, $position + 1);
$setter = "set" . ucwords($propertyName);
$to->$setter($value);
}
return $to;
}
We can call this function from the same namespace:
$object1= $this->setAllProperties($object2, $object1);
Upvotes: 0
Reputation: 11
Hacked away at this for a few hours and this is what i finally used. Note the parameters passed by reference in two places. One when you enter the method and the other in the foreach loop.
private function encryptIdsFromData(&$data){
if($data == null)
return;
foreach($data as &$item){
if(isset($item["id"]))
$item["id"] = $this->encrypt($item["id"]);
if(is_array($item))
$this->encryptIdsFromData($item);
}
}
Upvotes: 0
Reputation: 3236
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;
}
Upvotes: 6
Reputation: 584
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);
Upvotes: 2
Reputation: 353
You can implement Iterator interface and loop through the array of objects:
foreach ($objects as $object) {
$object->your_property = get_new_value();
}
Upvotes: 0