Why dynamically change the name of a variable in PHP?

Asked

Viewed 239 times

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?

  • 1

    The advantages of using this are debatable (tends to make code harder to read), but I gave an example here.

  • 1

    The name of it there is variable variables.

1 answer

1


Variable variant or variable, as you prefer to call it, can be used in n cases, but the most common of them is when you need to create a series of variables to apply in your system in a way that keeps a data exchange a little more secure than the use of global variables, for example. It allows you to minimize a little more your codes, to better understand note 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 that 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 it is not possible to use array, as the example below, even if you use array, it will still be a variant variable:

class Teste {

public $nome = 'Duds';

}  

$teste = new Teste();

$atributo_chamado = "nome";
echo $teste->{$atributo_chamado};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.