Call setter method with variable name

1.3k views Asked by At

What I'm asking here is something weird. I'm using Symfony2 with Doctrine2. To bypass a issue between FOSRestBundle and JMSBundle (who don't like composite primary key) I need to know if it's possible - and how - to call a setter from the name of the field.

Here an example: imagine my Product entity have a primary key composed by 3 fields. The trick is to send an array this kind of JSON into my API REST:

{
  "id": {
    "field1": "xxx",
    "field2": "...",
    "field3": "..."
  },
  // other fields
}

Then I use json_decode() to extract the ID field. I create a table of $key => $value with the 3 primary keys. And there is my problem, with this table I want, in a foreach loop, to do something like $myEntity->set$KEY($VALUE).

I'm doing this because I want to reuse this code with all my entities. I know that this is something really weird, to sum up with only the name of the object field/property I want to call is appropriate setter().

Thanks ;-)

PS: sorry if my English isn't perfect, this isn't my birth langage.

1

There are 1 answers

1
Raphaël Malié On BEST ANSWER

You can use dynamic method name in PHP :

$myEntity->{'set'.$KEY}($VALUE);

or more readable version :

$method = 'set'.$KEY;
$myEntity->$method($VALUE);

Don't forget to check if method exists anyway :

$method = 'set'.$KEY;
if (!method_exists($myEntity, $method))
  throw new \Exception('Something bad');
$myEntity->$method($VALUE);