Pass values ​​from an array to an object? - PHP

My problem is simplified:


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 in $ obj? (Obviously, without $ obj-> a = $ arr ["a"], suppose there are thousands of values)

Thank.

+3
source share
3 answers

Foreach loop and variable variable:

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

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

+6
source

You can also use a function get_class_vars(), for example -

<?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);
?>
+2
source

Same as (discarding protected and closed 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 the iterate method to 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
source

Source: https://habr.com/ru/post/1756095/


All Articles