Search code examples
phpdynamic-variables

PHP: How to use dynamic variable name with a class' setter


I have a class with a private member "description" but that proposes a setter :

class Foo {
  private $description;

  public function setDescription($description) { 
    $this->description = $description; 
  }
}

I have the name of the member in a variable. I would like to access the field dynamically. If the field was simply public I could do :

$bar = "description";
$f = new Foo();
$f->$bar = "asdf";

but I don't know how to do in the case I have only a setter.


Solution

  • <?php
    $bar = "description";
    $f = new Foo();
    $func="set"+ucwords($bar);
    $f->$func("asdf");
    ?>