Zuweisungsoperatoren

Der einfachste Zuweisungsoperator ist "=". Wahrscheinlich kommt man als erstes auf die Idee, ihn mit "ist gleich" zu bezeichnen. Das ist falsch. In Wirklichkeit bedeutet er, dass dem linken Operanden der Wert des Ausdrucks auf der rechten Seite zugewiesen wird (man müsste ihn also mit "wird gesetzt auf den Wert von" übersetzen).

Der Wert eines Zuweisungs-Ausdruckes ist der zugewiesene Wert. D.h. der Wert des Ausdruckes "$a = 3" ist 3. Das erlaubt es, einige raffinierte Dinge anzustellen:

<?php

$a 
= ($b 4) + 5// $a ist nun gleich 9 und $b wurde auf den Wert 4 gesetzt.

?>

Zusätzlich zu dem oben vorgestellten Zuweisungsoperator "=" gibt es "kombinierte Operatoren" für alle binären, arithmetischen, Array-Vereinigung- und String-Operatoren, die es erlauben, den Wert einer Variablen in einem Ausdruck zu benutzen, und dieser anschließend das Ergebnis des Ausdrucks als neuen Wert zuzuweisen. Zum Beispiel:

<?php

$a 
3;
$a += 5// setzt $a auf den Wert 8, als ob wir geschrieben haetten: $a = $a + 5;
$b "Hallo ";
$b .= "Du!"// setzt $b auf den Wert "Hallo Du!", aequivalent zu 
             // $b = $b . "Du!";
?>

Man beachte, dass die Zuweisung nur den Wert der Ursprungsvariable der neuen Variable zuweist (Zuweisung als Wert, sie "kopiert"), weshalb sich Änderungen an der einen Variable nicht auf die andere auswirken werden. Das kann wichtig sein, wenn man ein großes Array o. ä. in einer Schleife kopieren muss.

Eine Ausnahme vom üblichen Wertzuweisungsverhalten in PHP stellen Objekte (object) dar, die per Referenz zugewiesen werden. Objekte können mit dem clone Schlüsselwort explizit kopiert werden.

Referenzzuweisung

Referenzzuweisung wird ebenfalls unterstützt, unter Verwendung der "$var = &$othervar;" Syntax. Referenzzuweisung bedeutet, dass beide Variablen schließlich auf dieselben Daten zeigen, und nichts kopiert wurde.

Beispiel #1 Referenzzuweisung

<?php
$a 
3;
$b = &$a// $b ist eine Referenz auf $a

print "$a\n"// gibt 3 aus
print "$b\n"// gibt 3 aus

$a 4// ändere $a

print "$a\n"// gibt 4 aus
print "$b\n"// gibt ebenfalls 4 aus, da $b eine Referenz auf $a ist, das
              // geändert wurde
?>

Der new-Operator gibt automatisch eine Referenz zurück, sodass das Zuweisen des Ergebnisses von new per Referenz von PHP 7.0.0 an nicht erlaubt ist, von PHP 5.3.0 an einen Fehler der Stufe E_DEPRECATED, und in früheren Version einen Fehler der Stufe E_STRICT, auslöst.

Beispielsweise wird folgender Code einen Fehler oder eine Warnung auslösen:

<?php
class {}

$o = &new C;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe mit PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in …

Das oben gezeigte Beispiel erzeugt folgende Ausgabe mit PHP 5.3:

Deprecated: Assigning the return value of new by reference is deprecated in …

Das oben gezeigte Beispiel erzeugt folgende Ausgabe mit PHP 5:

Strict Standards: Assigning the return value of new by reference is deprecated in …

Weitere Informationen zu Referenzen und ihren Anwendungsmöglichkeiten sind dem Handbuch-Abschnitt Referenzen erklärt zu entnehmen.

Arithmetische Zuweisungsoperatoren

Beispiel Entsprechung Operation
$a += $b $a = $a + b Addition
$a -= $b $a = $a - $b Subtraktion
$a *= $b $a = $a * $b Multiplikation
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus

Bit-Zuweisungsoperatoren

Beispiel Entsprechung Operation
$a &= $b $a = $a & $b Bit-Und
$a |= $b $a = $a | $b Bit-Oder
$a ^= $b $a = $a ^ $b Bit-Xor
$a <<= $b $a = $a << $b Linksverschiebung
$a >>= $b $a = $a >> $b Rechtsverschiebung

Andere Zuweisungspperatoren

Beispiel Entsprechung Operation
$a .= $b $a = $a . $b Stringverknüpfung
$a ??= $b $a = $a ?? $b Null-Zusammenführungsoperator
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