I have a question about using variables as variablename.
I have an array with database fieldnames as key and object properties as values
like this:
$properties = array("userid" => "user['userid']", "city" => "hometown");
foreach ($properties as $field => $property ) {
$value1 = $db->$field;
$value2 = $obj->$property;
}
This works for the property hometown but doesn’t work voor de property user[‘userid’].
What is the correct way to adress the property variable?
I also tried several things like: ${property} or {$property} but without luck yet.
edit:
Thanks for all the responses! For now I’ll stay with my original solution, I was wondering if there was a way, I don’t have principal problems with the eval version, will keep it in mind!
foreach ($fields as $field => $property ) {
switch ($field) {
case "userid":
$newvalue = $this->user['userid'];
$oldvalue = $original->user['userid'];
break;
// more cases ...
default:
$newvalue = $this->{$property};
$oldvalue = $original->($property};
}
....
OK, so I decided to comment on this problem. Kai (no offence 🙂 provided you a solution which doesn’t use eval, but at the cost of additional 12 or so lines of code, making the code no doubt slower and more complex. So I myself think that in this case, it is justified to use eval() call. Hovewer, that could be just me (I value clear and short code a lot).
But beware, if input is coming from external sources, then you should filter it.