Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating an object's properties with an array?

Tags:

php

I want to take an array and use that array's values to populate an object's properties using the array's keynames. Like so:

$a=array('property1' => 1, 'property2' => 2);
$o=new Obj();
$o->populate($a);

class Obj
{
    function Populate($array)
    {
        //??
    }
}

After this, I now have:

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

How would I go about doing this?

like image 800
ryeguy Avatar asked Jan 23 '23 11:01

ryeguy


1 Answers

foreach ($a as $key => $value) {
    $o->$key = $value;
}

However, the syntax you are using to declare your array is not valid. You need to do something like this:

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

If you don't care about the class of the object, you could just do this (giving you an instance of stdClass):

$o = (Object) $a;
like image 162
Tom Haigh Avatar answered Jan 26 '23 02:01

Tom Haigh