Php Variable Reference Assignment Management

PHP already does a copy-on-write thing where it doesn't create a new value til you change something, so there's not much memory saved by using references. Doing so can even mess with some stuff PHP does internally to reduce memory usage, making things even worse.

Add to that the fact that references make things a bit too magical in general. The default, and thus what most people expect, is pass-by-value; when i pass to a function, it complicates things tremendously to have to care whether that function mysteriously changes to something else entirely, and thus make defensive copies just in case. (It can already modify if the value is an object, but in my opinion it shouldn't.)

Basically, i'd only find pass-by-reference useful for "out" parameters, meaning variables i expect to get back from the function rather than pass in, a la 's . Even for functions that clearly modify the object being passed in, like or , that feels a bit icky...but that's what we're stuck with.

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.


Leave a Reply

Your email address will not be published. Required fields are marked *