Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts

    Looping through an Object's members and changing its values

    Say I have:
    PHP Code:
    obj.one "Hello, World!"
    obj.two "Goodbye, World!"
    obj.three "Foo"
    obj.four "Bar" 
    1. How do I loop through it and change "o" to "a"?
    2. Make the changed value permanent (i.e. I changed it by reference)
    In PHP you, it's basically this:
    PHP Code:
    $v = (object)array('one' => "foooo"'two' => "bo");
    for( 
    $v => &$val ) {
    $val str_replace('o'$val);

    Last edited by Apothem; 11-21-2010 at 10:33 AM.

  • #2
    Regular Coder Samhain13's Avatar
    Join Date
    Aug 2008
    Location
    Pilipinas
    Posts
    169
    Thanks
    4
    Thanked 18 Times in 18 Posts
    You can use the object's internal dictionary (assuming "obj" is an instance of some object):

    Code:
    for o in obj.__dict__:
        obj.__dict__[o] = "some new value"
    If you have a source, like another dictionary that contains the same keys as the object's properties:

    Code:
    sauce = {"one": "some", "two": "value", "three": "here" }
    for k, v in sauce.items():
        # Do nothing if k is not a property of obj.
        if obj.__dict__.get(k):
            obj.__dict__[k] = v
    More to address your problem:
    Code:
    for key, value in obj.__dict__.items():
        obj.__dict__[k] = value.replace("o", "replacement text")
    Last edited by Samhain13; 11-21-2010 at 08:51 PM.
    I am a Man of Truth. I am a Free Human Person. I am a Peacemaker.
    ** Independent Multimedia Artist in Pasig **


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •