Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
Barth Avatar asked Jul 23 '12 12:07

Barth


People also ask

How to make Dynamic variable name in PHP?

The first is "take what's in the 12th element of the $donkeys array and use that as a variable name." Write this as: ${$donkeys[12]}. The second is, "use what's in the scalar $donkeys as an array name and look in the 12th element of that array." Write this as: ${$donkeys}[12].

How getters and setters work?

Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. A setter updates the value of a variable, while a getter reads the value of a variable.

Does PHP use getters and setters?

In this article, we learn the best way to create getter and setter strategies in PHP. Getter and setter strategies are utilized when we need to restrict the direct access to the variables by end-users. Getters and setters are methods used to define or retrieve the values of variables, normally private ones.


2 Answers

<?php
$bar = "description";
$f = new Foo();
$func="set"+ucwords($bar);
$f->$func("asdf");
?>
like image 60
Jerzy Zawadzki Avatar answered Nov 03 '22 02:11

Jerzy Zawadzki


Try this:

$bar = 'description';
$f = new Foo();
$f->{'set'.ucwords($bar)}('test');
like image 35
Jeff Lambert Avatar answered Nov 03 '22 03:11

Jeff Lambert