Operadores de asignación

El operador básico de asignación es "=". Se podría inclinar a pensar primero que es como un "igual a". No lo es. Realmente significa que el operando de la izquierda se establece con el valor de la expresión de la derecha (es decir, "se define como").

El valor de una expresión de asignación es el valor asignado. Es decir, el valor de "$a = 3" es de 3. Esto permite hacer algunas cosas intrincadas:

<?php

$a 
= ($b 4) + 5// ahora $a es igual a 9 y $b se ha establecido en 4.

?>

Además del operador básico de asignación, existen «operadores combinados» para todos los de aritmética binaria, unión de arrays y operadores de strings que permiten usar un valor en una expresión y entonces establecer su valor como el resultado de esa expresión. Por ejemplo:

<?php

$a 
3;
$a += 5// establece $a en 8, como si se hubiera dicho: $a = $a + 5;
$b "Hola ";
$b .= "ahí!"// establece $b en "Hola ahí!", al igual que $b = $b . "ahí!";

?>

Observe que la asignación copia la variable original en la nueva (asignación por valor), por lo que los cambios en una no afectarán a la otra. Esto también puede tener relevancia si se necesita copiar algo como un gran array dentro de un bucle estrecho.

Una excepción al comportamiento usual de la asignación por valor en PHP ocurre con objects los cuales son asignados por referencia en PHP 5. Los objetos pueden ser explícitamente copiados por medio de la palabra clave clone.

Asignación por referencia

La asignación por referencia también está soportada, utilizando la sintaxis "$var = &$othervar;". Asignación por referencia significa que ambas variables terminan apuntando a los mismos datos y nada es copiado en ninguna parte.

Ejemplo #1 Asignación por referencia

<?php
$a 
3;
$b = &$a// $b es una referencia para $a

print "$a\n"// muestra 3
print "$b\n"// muestra 3

$a 4// cambia $a

print "$a\n"// muestra 4
print "$b\n"// muestra 4 también, dado que $b es una referencia para $a, la cual ha
              // sido cambiada
?>

Desde PHP 5, el operador new retorna una referencia automáticamente, así que asignar el resultado de new por referencia, resulta en un mensaje E_DEPRECATED en PHP 5.3 y posteriores y un mensaje E_STRICT en versiones anteriores.

Por ejemplo, éste código resultará en una advertencia:

<?php
class {}

/* La siguiente línea genera el siguiente mensaje de error:
 * Deprecated: Assigning the return value of new by reference is deprecated in...
 */
$o = &new C;
?>

Más información sobre referencias y sus usos potenciales se puede encontrar en la sección del manual Referencias Explicadas

add a note add a note

User Contributed Notes 8 notes

up
93
Peter, Moscow
13 years ago
Using $text .= "additional text"; instead of $text =  $text ."additional text"; can seriously enhance performance due to memory allocation efficiency.

I reduced execution time from 5 sec to .5 sec (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end.
up
56
Robert Schneider
9 years ago
Be aware of assignments with conditionals. The assignment operator is stronger as 'and', 'or' and 'xor'.

<?php
$x
= true and false;   //$x will be true
$y = (true and false); //$y will be false
?>
up
30
Hayley Watson
16 years ago
bradlis7 at bradlis7 dot com's description is a bit confusing. Here it is rephrased.

<?php
$a
= 'a';
$b = 'b';

$a .= $b .= "foo";

echo
$a,"\n",$b;?>
outputs

abfoo
bfoo

Because the assignment operators are right-associative and evaluate to the result of the assignment
<?php
$a
.= $b .= "foo";
?>
is equivalent to
<?php
$a
.= ($b .= "foo");
?>
and therefore
<?php
$b
.= "foo";
$a .= $b;
?>
up
6
asc at putc dot de
8 years ago
PHP uses a temporary variable for combined assign-operators (unlike JavaScript), therefore the left-hand-side (target) gets evaluated last.

Input:
$a += $b + $c;

Meaning:
$a = ($b + $c) + $a;

Not:
$a = $a + ($b + $c);

This can be important if the target gets modified inside the expression.

$a = 0;
$a += (++$a) + (++$a); // yields 5 (instead of 4)
up
-15
ma dot bx dot ar at gamil dot com
9 years ago
Document says:
"An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword."

But it's not very accurate! Considering this code:
<?php
$a
= new StdClass;
$b = $a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output:
object(stdClass)#2 (0) {
}
object(stdClass)#1 (0) {
}
Note: #2 and #1 means two different objects.

But this code:
<?php
$a
= new StdClass;
$b = &$a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output will be:

object(stdClass)#2 (0) {
}
object(stdClass)#2 (0) {
}

Note: Still pointing to the same object.

And this shows that that exception is not valid, PHP assignment for objects still makes a copy of variable and does not creates a real reference, albeit changing an object variable members will cause both copies to change.
So, I would say assignment operator makes a copy of 'Object reference' not a real object reference.
up
-14
Hayley Watson
16 years ago
You could also take adam at gmail dot com's xor-assignment operator and use the fact that it's right-associative:

$a ^= $b ^= $a ^= $b;
up
-31
bradlis7 at bradlis7 dot com
18 years ago
Note whenever you do this

<?php
$a
.= $b .= "bla bla";
?>

it comes out to be the same as the following:

<?php
$a
.= $b."bla bla";
$b .= "bla bla";
?>

So $a actually becomes $a and the final $b string. I'm sure it's the same with numerical assignments (+=, *=...).
up
-46
haubertj at alfredstate dot edu
12 years ago
[[   Editor's note: You are much better off using the foreach (array_expression as $key => $value) control structure in this case   ]]

When using

<php
while ($var = current($array) {
#do stuff
next($aray)
?>

to process an array, if current($array) happens to be falsy but not === false it will still end the loop.  In such a case strict typing must be used.

Like this:

<php
while (($var = current($array)) !== FALSE) {
#do stuff
next($aray)
?>

Of course if your array may contain actual FALSE values you will have to deal with those some other way.
To Top