id <- I have such...">

$ this & # 8594; "variable value" OOP PHP

I am wondering if this is possible, and just in case, how can I achieve this:

$this->id <- I have such a thing. but to make it more convenient, I would like to have $this->(and here to change the values)

for ex: I can have $this->id $this->allID $this->proj_id

how can i make it so that i actually have $this->($myvariable here, that has a unique name in it) ?

+4
source share
4 answers

You can simply use this:

  $variable = 'id'; if ( isset ( $this->{$variable} ) ) { echo $this->{$variable}; } 
+8
source

Here is the solution: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

Usage example here:

 class myClass { /** Location for overloaded data. */ private $myProperties = array(); public function __set($name, $value) { $this->myProperties[$name] = $value; } public function __get($name) { if (array_key_exists($name, $this->myProperties)) { return $this->data[$name]; } } } 
+1
source

You should check the manual variable variables on the PHP site. However, it may look like this:

 <?php echo ${'this->'.$yourvariable}; ?> 
0
source

I prefer to use call_user_func and pass parameters as array .

 public function dynamicGetterExample() { $property = 'name'; // as an example... $getter = 'get'.ucfirst($property); $value = call_user_func(array($this,$getter)); if (empty($value)) { throw new \Exception('Required value is empty for property '.$property); } return $value; } 
0
source

All Articles