What utility has this form of accessing variable values

Posted on

Question :

      $Bar = "a";
      $Foo = "Bar";
      $World = "Foo";
      $Hello = "World";
      $a = "Hello";



How can I take advantage of this way of accessing value of php variables in this way, in the practice in which it would be useful?


Answer :

Variable variables, dynamic variables, or even variables created during execution in PHP.

It is a feature that allows us to create a variable through the contents of another variable.

To create a variable variable you use one variable to serve as an identifier for another variable that is created. For this we use the symbol $ twice, that is, we must use $$ . See the example below.


// Declarando o valor da variável $a

$a = 'nome';


 * Criamos $$a, que como possui dois $

 * também pode ser chamada pelo valor da

 * variável $a ou seja "nome"


$$a = 'Mauro';

// Exibo $a e $nome que foi criada dinâmicamente

echo $a . ' : ' . $nome;


As you can see in the example we can create the variable from the value of another variable. The opposite is also valid instead of creating the variable, in our case, $nome dynamically we define its value normally however when we show its result on screen we can access its value through $$a , remembering that for this to work $a must have the same value as the variable that will be created in our “name” case. In this other example, using your question, see what the outputs look like:

  $Bar = "a";
  $Foo = "Bar";
  $World = "Foo";
  $Hello = "World";
  $a = "Hello";

  $a; //Retorna Hello
  $$a; //Retorna World
  $$$a; //Retorna Foo
  $$$$a; //Retorna Bar
  $$$$$a; //Retorna a

  $$$$$$a; //Retorna Hello
  $$$$$$$a; //Retorna World

In my opinion, day-to-day this has no commercial utility, but rather for studies, to learn how variables created in execution work.

Fonte 1 Source 2 and Comments

PS: See the answer from @bfavaretto in this question here , will give you an idea of actual usage.


Another opinion


Dynamic variables have utility, as can be seen in the following example.

In sending an long form instead of typing trocars times in the code, such as $nome = $_POT['nome']


By making use of dynamic variables the thing becomes very simplified, see how

foreach ( $_POST as $chave => $valor ) {
  // $$chave cria as variáveis com os names dos elementos do formulário
  $$chave = trim( strip_tags( $valor ) );

I’ll cite another example of using these Variáveis variáveis, variáveis dinâmicas ou ainda variáveis criadas durante a execução no PHP

I have a hundred options as exemplified below:

echo ("<option value="youtube.php?n=s5&





Leave a Reply

Your email address will not be published. Required fields are marked *