ryeguy
ryeguy

Reputation: 66851

Populating an object's properties with an array?

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?

Upvotes: 4

Views: 5331

Answers (2)

Tom Haigh
Tom Haigh

Reputation: 57815

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;

Upvotes: 12

poundifdef
poundifdef

Reputation: 19363

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
...

Upvotes: -3

Related Questions