Jump to content

Variable varibles with array.


genetheblue

Recommended Posts

Hi I'm trying to use variable variables to access fields from a db. I have code that works, but I don't understand why I need to declare it as a variable outside of the array as well.

 

What I have:

$fname = 'fname'; // Why do I need this??

$fieldList = array('fname');

$output = $row->${fieldList[0]};

 

This works, however... if I leave out $fname='fname' it does not work. I read the docs, and tried $output = $row->${fieldList}[0] but that doesn't make sense when accessing a property of the row object.

 

Is this the way it is, or am I doing something wrong that I need to double up on my field declarations to get them as a passable array? This way, I will need to declare every field in the db I want, then put it in the array which just seems strange.

 

Thanks for any help...

Link to comment
https://forums.phpfreaks.com/topic/65130-variable-varibles-with-array/
Share on other sites

Thanks for the response,

 

... but I'm trying to get this in a function so I can pass an array of fields, and loop through them - using the array elements as my field accessor(?)).

 

I don't want to hardcode fname into the loop. I will have another loop to build a table based on which fields are passed in the array I'm trying to use.

 

 

The error message(sorry dumb to leave that out!) before was 'Cannot access empty property'.

 

If I use $output = $row[${$fieldList[0]}]; I get an error:

'Cannot use object of type stdClass as array'

 

 

However, if I simply use 1 variable in my loop...

$curField = fieldList[ii];

$row->${$curField}

 

It works without me having to declare variables all over the place - I can just declare my array and pass it like I wanted. I still don't fully understand why, so if anyone can educate me great. I'm also still trying to find a good debugger that hopefully isn't expensive! I feel lazy starting php and wishing I could watch my objects in real time :) It would be nice to be able to watch these objects - but just the nature of web development states(or lack of) is still newer to me.

 

But I do have a solution that isn't making me cringe everytime I want to call this function.

 

Thanks much....

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.