I have this class,
class example {
public $a;
public $b;
public $c;
....
}
I have an array containing equal number of public variables as present in the example class (in this case 3):
$arr[0] = 'Red';
$arr[1] = 'Green';
$arr[2] = 'Blue';
I want to assign each value of this array to the public properties of the class one by one (Like $a gets Red, $b gets Green and so on). How do I assign these values from the array to the public properties of the class using a loop?
I was writing something like below, but it didn't work:
$class = new example();
$i = 0;
foreach ($class as $key => $value) {
$class->$$key = $arr[$i];
$i++;
}
EDIT:
Just to explain why I couldn't use any setter/getter method in example class - actually example class is created by unserializing a database object. I do not have any control on this class. I am working on a controller class which receives this example class and an array. I need to figure out a way to assign the values from this array to the public properties of example class.
$class->0or$class->1members. There are hackish ways to achieve it, but we'll settle on that you can't. However, your entire approach is wrong. Why doesn't your class have an array instead of a number of public members?$keyis not a number, it's the name of the public member properties ofexampleclass.