How do I dynamically update a classes properties?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Samishii23
    New Member
    • Sep 2009
    • 246

    #1

    How do I dynamically update a classes properties?

    So I have a data class that has a bunch of properties that reflect a Business' information, like address, phone, etc.. I have the constructor setting all the information via $id being passed, which is used to pull data from the DB.
    Then I have a method, set($id), that will update those properties with a new set of information gathered from the database.

    The code is kinda long, and makes me annoyed cause I have 8 lines of code that just set each property individually. I don't like it.

    I feel like a bad coder doing this so I wanna know if theres a way to dynamically loop through each properly to set it rather then set each separately.

    Quickie mock up:
    Code:
    foreach ($dbdata as $k => $v) {
       $this->{$k} = $v; }
    I have no idea if that works. I thought I seen an example like that a little while ago, but I can't find it again. So. I wanna know how to do something like this.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    do you want to edit the properties "manually" or update them from DB? for the latter there are a couple of PDO fetch options that can do that.

    Comment

    • Samishii23
      New Member
      • Sep 2009
      • 246

      #3
      Basicly the properties will be named the same as the database table columns. So I suppose the latter would work? Though if its possible to do outside of PDO functions, then I would like to know how to do both. :)

      Comment

      • Markus
        Recognized Expert Expert
        • Jun 2007
        • 6092

        #4
        Sounds like you're building something in the vein of ORM (Object-Relational Mapping). There are libraries out there for PHP that will do this for you out-of-the-box, for example, Doctrine.

        Mark.

        Comment

        Working...