1

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

S S
  • 1,443
  • 2
  • 12
  • 42
  • 2
    you’re trying to call a method, but are instead setting a property. Calling a method works the same way, except with parentheses. See this: https://stackoverflow.com/questions/1005857/how-to-call-a-function-from-a-string-stored-in-a-variable – BenderBoy Oct 11 '21 at 09:16

1 Answers1

4

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!
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    To go further, you could also check the existence of the method before calling her (method_exists). – SeeoX Oct 11 '21 at 09:32
  • Thanks. It works. `if (method_exists($record, $label)) { $customer->{$label}($value); }` – S S Oct 12 '21 at 03:54