PHP how to use a variable value as the name of a new variable?

jryan21

Level 4 Grindstone
Nov 10, 2007
5,448
108
0
I'm getting a php notice because I'm introducing a new variable as an object attribute without first declaring it.

I have something like:

Code:
function get_stuff_from_db($mytable, $field_name)
{
   $myquery = select_all_from($mytable); // returns a mysql result object 
   
   foreach($myquery->result() as $row)
      echo $row->$field_name;

}

and the notice is on the field name, so if the actual field name is 'id', I would get:
Undefined property: stdClass::$id

I've tried enclosing in {}, using $$, but it always leads back to the same problem.

How can I declare $id using $field_name ?