CakeFest 2017 NYC, the Official CakePHP Conference

Was Referenzen sind

Referenzen sind in PHP ein Mechanismus um verschiedene Namen für den gleichen Inhalt von Variablen zu ermöglichen. Sie sind nicht mit Zeigern in C zu vergleichen, sondern Aliasdefinitionen für die Symboltabelle. PHP unterscheidet zwischen Variablenname und Variableninhalt, wobei der gleiche Variableninhalt unterschiedliche Namen besitzen kann. Der bestmögliche Vergleich ist der mit Dateinamen und Dateien im Dateisystem von Unix - Variablennamen sind Verzeichniseinträge, während der Variableninhalt die eigentliche Datei darstellt. Referenzen können nun als Hardlinks im Dateisystem verstanden werden.

add a note add a note

User Contributed Notes 2 notes

1 month ago
In summary, "&$reference" means "do-not-copy-on-write the value here, in perpetuity". Assigning by reference is not assignment, it's "make &$variable a reference and its value do-not-copy-on-write, in perpetuity, and make the variable I'm assigning to use that do-not-copy-on-write value as well".

To "unreference/unalias" you have to either unset or make an explicit copy into a new variable.

Object properties that are references will survive cloning and remain references. Generally the same is true with references in arrays and PHP's array functions (combine, intersect, call_user_func, func_get_args, etc).

Calling a function that uses a reference parameter will *make* the supplied variable a reference. This is also true when using variadic array expansion for arguments; the supplier's array element will become a reference.

Generally, don't use them unless you're dealing with low-level calls, or need an accumulator, etc. For poorly designed functions that use them, give them a copy to mangle.
10 months ago
One subtle effect of PHP's assign-by-reference is that operators which might be expected to work with args that are references usually don't.  For example:

$a = ($b ? &$c : &$d);

fails (parser error) but the logically identical

if ($b)
   $a =& $c;
   $a =& $cd;

works. It's not always obvious why seemingly identical code throws an error in the first case. This is discussed on a PHP bug report ( ). TL;DR version, it acts more like an assignment term ($var1) "=&" ($var2) than a function/operator ($var1) "=" (&$var2).
To Top