Why are PHP references a bad idea? How do zvals an

2019-08-25 02:20发布

问题:

I've recently discovered that using references in PHP is generally (although not always) a bad idea from a memory management or performance point of view, because of Copy On Write and the way that variables are represented under the hood using zvals.

Can someone offer a fuller explanation? I have seen this link posted a few times on Stack Overflow: http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html

I also found this reference, which goes into a bit more detail about zvals and how they work. It's in French though, although Google does a pretty good job of translating it: http://julien-pauli.developpez.com/tutoriels/php/internals/variables/

I'm surprised there isn't any more, or better documentation on this, and I wondered if any other Stack Overflow users have come across any clearer or more accessible documentation that I haven't been able to find?

回答1:

Sara Golemon has an interesting article at http://blog.golemon.com/2007/01/youre-being-lied-to.html

The moral of the story

Assigning values by references when you don't need to ... is NOT a case of you outsmarting the silly engine and gaining speed and performance. It's the opposite, it's you TRYING to outsmart the engine and failing, because the engine is already doing a better job than you think.

And some background on zvals in general. But both these are a bit old. Not sure how much has changed over the years.