The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:
Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.
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.
Assignment by Reference
Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.
Example #1 Assigning by reference
As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an message in PHP 5.3 and later, and an message in earlier versions.
For example, this code will result in a warning:
More information on references and their potential uses can be found in the References Explained section of the manual.
14 years ago
7 years ago
2 years ago
10 years ago
3 years ago
2 years ago
10 years ago
12 years ago
6 years ago
It's not deprecated and is unlikely to be. It's the standard way to, for example, make part of one array or object mirror changes made to another, instead of copying the existing data.
It's called assignment by reference, which, to quote the manual, "means that both variables end up pointing at the same data, and nothing is copied anywhere".
The only thing that is deprecated with is "assigning the result of by reference" in PHP 5, which might be the source of any confusion. is automatically assigned by reference, so is redundant/deprecated in, but not in .
Since it's hard to search, note that (equals ampersand) is the same as (equals space ampersand) and is often written such that it runs into the other variable like or (ampersand dollar sign variable name). Example simplified from the docs:
Here's a handy link to a detailed section on Assign By Reference in the PHP manual. That page is part of a series on references - it's worth taking a minute to read the whole series.