Filling an object's properties with an array?

I want to take an array and use these array values ​​to populate the properties of an object using the array key names. For instance:

$a=array('property1' => 1, 'property2' => 2); $o=new Obj(); $o->populate($a); class Obj { function Populate($array) { //?? } } 

After that I now have:

 $o->property1==1 $o->property2==2 

How can I do it?

+4
source share
2 answers
 foreach ($a as $key => $value) { $o->$key = $value; } 

However, the syntax you use to declare your array is invalid. You need to do something like this:

 $a = array('property1' => 1, 'property2' => 2); 

If you don't need an object class, you can simply do this (by giving you an instance of stdClass ):

 $o = (Object) $a; 
+12
source

Hm. How about something like

 class Obj { var properties = array(); function Populate($array) { this->properties = $array; } } 

Then you can say:

 $o->properties['property1'] == 1 ... 
-3
source

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


All Articles