Home > Back-end >  How to dynamically set an object property value?
How to dynamically set an object property value?

Time:10-11

I have a customer object data:

App\Entity\Customer {#661
    -id: 100003
    -manufacturer: "TEST A"
    -description: "This is a description"
    ...
    ...
    ...
}

From an array which consist of column name I need to reset the object value.

From the array, with a loop:

foreach ($user as $key => $value) {
    if ($key === 'manufacturer') {
        $customer->setManufacturer($value);
    }

    if ($key === 'description') {
        $customer->setDescription($value);
    }
   ... and so on...
}

Is it possible to dynamically set the object without making multiple if condition.

I have tried following:

$label = 'set' . ucfirst($key);
$tyre->{$label} = $value;

But it is not updating the object instead adding

Appended label

CodePudding user response:

Your approach is fine, but you should call the (dynamically named) method, not assign to it:

foreach ($user as $key => $value) {
    $label = 'set' . ucfirst($key);
    $customer->{$label}($value); // <-- call it!
}
  •  Tags:  
  • php
  • Related