Wednesday 24 August 2016

Reference assignment operator in PHP, =&



What does the =& (equals-ampersand) assignment operator do in PHP?



Is it deprecated?


Answer



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 new by reference" in PHP 5, which might be the source of any confusion. new is automatically assigned by reference, so & is redundant/deprecated in$o = &new C;, but not in $o = &$c;.






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 $x = &$y['z']; or $x = &$someVar (ampersand dollar sign variable name). Example simplified from the docs:



$a = 3;

$b = &$a;
$a = 4;
print "$b"; // prints 4





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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...