Connecting Tech Pros Worldwide Forums | Help | Site Map

referring to an object member

Rainman
Guest
 
Posts: n/a
#1: Dec 20 '05
I have an object ($obj) that contains members 'sunday', 'monday',
'tuesday', 'wednesday', etc. I can refer to them in my code as
$obj->sunday, etc. But I want to refer to these members in a loop, such as:

$dow = array('sunday','monday','tuesday',...);

foreach ($dow as $day) {
print $obj->$day;
}

But this syntax does not work. I tried eval() and a few other things
with {}, but all failed.

Can I do this sort of thing? If so, what's the correct syntax?
Mark

cross at php net
Guest
 
Posts: n/a
#2: Dec 20 '05

re: referring to an object member


Hrm, why do you have each day as a seprate member variable?

I would set it up as , an example:
$obj->dayOfWeek['sunday']

dayOfWeek being an array to hold each of the separate days data.....

Rainman
Guest
 
Posts: n/a
#3: Dec 21 '05

re: referring to an object member


cross at php net wrote:[color=blue]
> Hrm, why do you have each day as a seprate member variable?[/color]

Well, because it comes from the database that way where there are
columns named 'sunday,'monday','tuesday', etc. I can't change the database.[color=blue]
>
> I would set it up as , an example:
> $obj->dayOfWeek['sunday']
>
> dayOfWeek being an array to hold each of the separate days data.....
>[/color]
This requires changing the database, or adding substantial code to fake
it. Is there no simpler way to refer to it similar to this: $obj->$dow
where $dow could be 'sunday, 'monday', etc.?

Mark
Chung Leong
Guest
 
Posts: n/a
#4: Dec 21 '05

re: referring to an object member


That is the correct syntax. It should work. Are you sure the names are
correct? Do post the result of print_r() on one of these objects.

Maybe you should consider storing your rows in associative arrays
instead. It's more obvious.

Rainman
Guest
 
Posts: n/a
#5: Dec 21 '05

re: referring to an object member


Chung Leong wrote:[color=blue]
> That is the correct syntax. It should work. Are you sure the names are
> correct? Do post the result of print_r() on one of these objects.
>[/color]
Thanks! Now that I have this assurance that my syntax is right, I'm
been able to determine my problem existed elsewhere, and I've fixed it.
Mark
Closed Thread