What is the reason for dynamically changing the name of a variable in PHP?

0

In PHP, you can dynamically change the name of a variable using $$ . But what is the reason for this possibility? What is its applicability?

    
asked by anonymous 05.10.2015 / 20:07

1 answer

1

Variable variant or variable variable, as you prefer to call it, can be used in n cases, but the most common of these is when you need to create a series of variables to apply to your system in a way that holds an exchange of data in a slightly more secure way than the use of global variables, for example. It allows you to minimize your codes a bit, to better understand the following example:

// fazendo um post através de uma requisição, imagine quantas linhas eu economizei tendo que escrever cada uma destas variáveis:
$campos = ['nome','email','senha','cidade','uf'];
foreach ($campos as $campo) {
         ${$campo} = sanitize($_REQUEST[$campo]); //usa os filtros automáticos do PHP
}

Imagine my form had more than 200 fields, and I had to write them manually, like this:

$nome = sanitize($_REQUEST['nome']);
$email = sanitize($_REQUEST['email']);
$senha = sanitize($_REQUEST['senha']);
$cidade = sanitize($_REQUEST['cidade']);
$uf = sanitize($_REQUEST['uf']);
...

I would already be sleeping in the middle of this production before reaching the hundredth. Of course you can also do this using array:

 $campos = ['nome','email','senha','cidade','uf'];
  foreach ($campos as $key => $campo) {
            $campos[$key] = sanitize($_REQUEST[$campos[$key]]); //usa os filtros automáticos do PHP
    }

But there are cases that you can not use array, as the example below, even if you use array, is still being a variant variable:

class Teste {

public $nome = 'Duds';

}  

$teste = new Teste();

$atributo_chamado = "nome";
echo $teste->{$atributo_chamado};
    
05.10.2015 / 21:25