PHP variable reference problems: further insight
Published September 15th, 2005After my previous post about changes to PHP 4.4 and 5.0.5 generating new errors, I’ve been following with interest various discussions on the issue. In particular, I’ve been keeping my eye on the PHP Internals mailing list, where there have been a number of (ahem) ‘lively’ debates among the very people responsible for the development of the language (including the likes of Rasmus Lerdorf and Zeev Suraski).
Apart from some quite entertaining bitching, one useful insight has come to light regarding the way PHP handles the passing around of variables internally. It’s explained most clearly by Zeev in this post (Zeev’s comments in bold):
For performance’ sake, I have to know if this is true:
Is it the case that when I do this:
< ?php
$array = array(”one” => array(0,1,2), “two” => array(4,5,6));
$one = $array["one"];
?>That $one is not a copy, but a reference to $array["one"] and will only become a copy when I alter the contents of $one?
That’s correct.
I know this is the case for regular variables, but does this also go for contents of arrays? If not, I need to use the ampersand like I used to. But if it really is just a reference, that would be good to know as I shouldn’t be using the ampersand at all (mistakingly thinking it’s a performance advantage when it’s actually not).
Generally, using & where it’s not necessary is more often than not a performance disadvantage, and not an advantage. You should never use & for better performance, only if you need it for applicative usage. The engine would do its best to do the least copying on its own.
So if you don’t modify the contents of a variable, PHP doesn’t bother making a copy of it, internally — it just passes around a reference (whether you tell it to or not). Now I’ve never really used references explicitly much, but I have a colleague who routinely uses passing by reference because he believes it improves performance.
So while I generally object to the idea that a developer like me must have intimate knowledge of the internal workings of PHP to be able to work with it effectively, in some cases clearly it’s an advantage.
Leave a comment
Comment Policy: First time comments are moderated. Please be patient.