Is it possible to have a construct like this. Say I have an array like this:
$names = array ('name1', 'name2', 'name3');
$values = array ('value1', 'value2', 'value3');
And then I want to do the following:
foreach ($names as $field) {
$this->$field = $values[$counter];
$counter ++;
}
So that later, I can access the said object like this:
$var1 = $object->name1;
$var2 = $object->name2;
// produces "value1"
echo $var1;
// produces "value2"
echo $var2;
What I want to do is to have an object, that has dynamically named fields. Is this possible with OO PHP?
Yes, you can
As suggested by @Sam, the Magic __set method works better
Using a specially-configured ArrayObject, you can access members using either syntax:
Yep, that'll work, but generally Variable Variables are discouraged.
Perhaps the more elegant solution would be to use the __get magic method on the class like so:
The vars array would then work as so:
Or if you specifically want to build it from the two arrays: