Correct way to value a PHP variable

0

I got a system to do maintenance, but I came across the following excerpt:

$nomeUsuario = $_SESSION["NomeUsuario"] = $idUsuario;

It works, but I confess that I use the traditional way:

$nomeUsuario = $_SESSION["NomeUsuario"];
$idUsuario = $nomeUsuario;

Can the first mode, although it work, be used?

    
asked by anonymous 11.05.2018 / 11:28

1 answer

4

Attribution Operators

  

The left operand receives the value of the right expression

That is, you can chain several variables to the same value, because the left variable will get the value of the right variable.

Example:

In multi-line format

$var_a = 'A';
$var_b = 'A';
$var_c = 'A';
$var_d = 'A';
$var_e = 'A';

Single Line Assignment

$var_a = $var_b = $var_c = $var_d = $var_e = 'A';

Given your example:

$nomeUsuario = $_SESSION["NomeUsuario"];
$idUsuario = $nomeUsuario;

Verified based on your first example, this second example is not supported. Because $nomeUsuario and $_SESSION["NomeUsuario"] will have the value of $idUsuario .

So this assignment $idUsuario = $nomeUsuario; is not true;

Functional Example

Conclusion:

The assignment format will depend on what you really need, assignment on a single line is useful for assigning the same value to multiple variables. This reduces the amount of manual assignment you need to perform.

This other example is also functional, an assignment in a sum.

$a = ($b = 4) + 5; // $a é igual a 9 agora e $b foi definido como 4.
    
14.05.2018 / 20:58