Dynamically named variables

  • PHP - November 17, 2016

Sometimes you just need your variable be be named dynamicly, from an existing variable that changes its vlaue or a value from a database or an array.

Well it could'nt be simpler:

${"StaticName_".$myVariable}

 


An example of this is when you need a part of a class name to dynamicly change:

if ($variable == 1) {
  $myVariable = "One";
} else {
  $myVariable = "Two";
}

${"className_".$myVariable}

/*
variable name = $classNameOne;
or
variable name = $classNameTwo; 
*/

 

Comments