28.13. Don't Pass by Reference (or, Don't Trust Your Instincts)

Telling people not to trust their instincts may be startling, but in the context of PHP it can be good advice. One of the most common examples of a popular bad hunch is the urge to pass variables by reference for performance reasons. Admittedly, it sounds very convincing. Instead of passing a copy of the variable, a script passes the variable itself. That's bound to be faster, isn't it? Well, no. In order to understand why, we need to understand a bit more about how the Zend Engine handles values.

The Zend Engine implements a reference-counted, copy-on-write value system. This means that multiple variables may point to the same value without consuming multiple blocks of memory. Consider ...

Get Core PHP Programming, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.