tags:

views:

46

answers:

3

My problem, simplified is:


class A {
  public $a;
  public $b;

  function f1 () {
     // Code
  }
}

$obj = new A();

$arr = array ("a" => 1, "b" => 2);

How can I put the contents of $arr into $obj? (Obviously without $obj->a = $arr["a"], suppose there are thousands of values)

Thank you.

+6  A: 

A foreach loop and a variable variable:

foreach ($arr as $name => $value) {
  $obj->$name = $value;
}

You probably shouldn't have thousands of variables in your class though.

yjerem
Thank you very much. :)
john
+2  A: 

You can also use get_class_vars() function like -

<?php
class A {
  public $a;
  public $b;

  function f1 () {
     // Code
  }
}    

$obj = new A();   

$arr = array ("a" => 1, "b" => 2);

$vars = get_class_vars("A");

foreach($vars as $var=>$value)
    $obj->$var = $arr[$var];

print_r($obj);
?>
Shubham
Thank you for answering!
john
+1  A: 

A same as (discarding protected & private member):

foreach ($obj as $property_name => $property_value) {
    if (array_key_exists($property_name, $arr))
        //discarding protected and private member
        $obj->$property_name = $arr[$property_name];
}

Or just add iterate method on class A:

class A {
    public $a;
    public $b;

    function iterate($array) {
        foreach ($this as $property_name => $property_value) {
            if (array_key_exists($property_name, $array))
                $this->$propety_name = $array[$property_name];
        }
    }
    function f1 () {
        // Code
    }
} 

and use the iterate() method.

iroel
The last code will affecting private and protected member in contrast the previous code. So choose according to your needs.
iroel
Many thanks for your reply!
john