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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
?>

Comments

1

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.

1 Comment

The last code will affecting private and protected member in contrast the previous code. So choose according to your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.