PHP – Why Are References Rarely Used in PHP?

PHPreference

I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods.

Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it.

I have read that using references uses less memory, so why aren't they used in PHP?

Best Answer

Your assertion that references are rarely used is incorrect. As others have already mentioned there's a ton of native functions that use references, notable examples include the array sorting functions and preg_match() / preg_match_all(). If you are using any of these functions in your code, you are also using references.

Moving on, references in PHP are not pointers. Since you're coming from a C++ background I can understand the confusion, but PHP references are an entirely different beast, they are aliases to a symbol table. Any performance gains you might have expected from C++ references simply don't apply to PHP references.

In fact, in most scenarios passing by value is faster and less memory intensive than passing by reference. The Zend Engine, PHP's core, uses a copy-on-write optimization mechanism that does not create a copy of a variable until it is modified. Passing by reference usually breaks the copy-on-write pattern and requires a copy whether you modify the value or not.

Don't be afraid to use references in PHP when you need to, but don't just do it as an attempt to micro-optimize. Remember, premature optimization is the root of all evil.

Further reading: