tags:

views:

177

answers:

2

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?

+7  A: 
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;
Tom Haigh
Wow, I almost feel stupid. Thanks.
ryeguy
Woops on the array too, that's my new language which is a merge of PHP and python :p
ryeguy
A: 

Hm. What about having something like

class Obj
{

    var properties = array();

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

Then you can say:

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