sprugman
sprugman

Reputation: 19831

access a property via string with array in php?

I have a big list of properties that I need to map between two objects, and in one, the value that I need to map is buried inside an array. I'm hoping to avoid hard-coding the property names in the code.

If I have a class like this:

class Product {
    public $colors, $sizes;
}

I can access the properties like this:

$props = array('colors', 'sizes');
foreach ($props as $p) {
    $this->$p = $other_object->$p;
}

As far as I can tell, if each of the properties on the left are an array, I can't do this:

foreach ($props as $p) {
    $this->$p[0]['value'] = $other_object->$p;
}

Is that correct, or am I missing some clever way around this?

(This is in drupal, but I don't really think that matters.)

Upvotes: 0

Views: 255

Answers (4)

Mark Tomlin
Mark Tomlin

Reputation: 8933

foreach ($props as $p) {
    $this->{$p}[0]['value'] = $other_object->{$p};
}

It's called variable, variables.

Upvotes: 0

mike clagg
mike clagg

Reputation: 840

Also try this:


$props = get_object_vars($this);

Upvotes: 1

awgy
awgy

Reputation: 16924

I believe you can wrap it in curly braces {}:

foreach ($props as $p) {
    $this->{$p}[0]['value'] = $other_object->$p;
}

Edit:

Okay. Now my brain turned on. Sorry for the confusing edits.

Upvotes: 4

Artefacto
Artefacto

Reputation: 97835

I don't understand your problem. This works:

class Test {
    public $prop = "prov value";
}
$arr = array(array("prop"));
$test = new Test();
$test->$arr[0][0] = "new prop value";
var_dump($test);

result:

object(Test)#1 (1) {
  ["prop"]=>
  string(14) "new prop value"
}

Upvotes: -1

Related Questions