4

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?

2 Answers 2

12
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;
Sign up to request clarification or add additional context in comments.

1 Comment

Woops on the array too, that's my new language which is a merge of PHP and python :p
-3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.