referring to an object member

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rainman

    referring to an object member

    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','tuesd ay',...);

    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

    #2
    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.....

    Comment

    • Rainman

      #3
      Re: referring to an object member -- still questions

      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

      Comment

      • Chung Leong

        #4
        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.

        Comment

        • Rainman

          #5
          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

          Comment

          Working...