Correct way to give value to a PHP variable

Asked

Viewed 55 times

0

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

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

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

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

The first mode, although working, can be used?

  • 3

    If you think it’s legible, you can.

  • 2

    It’s pretty personal this, how to use if or ternary for example, but can be used yes

  • 1

    Just as @Ricardopunctual said is very personal, I usually use $a=$b=$c, but in both the operation is the same and can be used.

1 answer

4

Allocation Operators

The left operand takes the value of the right expression

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

Example:

In multiple line format

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

Single line allocation

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

Given his example:

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

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

Therefore this assignment $idUsuario = $nomeUsuario; it’s not true;

Functional Example

Completion:

The assignment format will depend on what you really need, the assignment in a single row is useful for assigning the same value to multiple variables. Thus 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.

Browser other questions tagged

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