Thursday, August 18, 2011

avoid pass by reference in PHP

One of my post (http://hengrui-li.blogspot.com/2011/08/php-copy-on-write-how-php-manages.html) discusses PHP's copy on write mechanism and explain why passing by value won't cost more memory in most cases.

Actually, pass by reference in PHP is considered as a bad practice, even from the perspective of performance. Today i found these two very valuable posts about PHP's reference mechanism. It definitely worths a read:

1. http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html
2. http://schlueters.de/blog/archives/141-References-and-foreach.html

Both posts from the same guy and his English is much better than mine. Anyway, here quotes from the summary of his post: "Do not use references for performance". And he explains the reason very well.


We should try to avoid using pass by reference in php. The reason is quite simple and common: when we have a lot of references in our system, changing one will change another and it will be hard for us to track what happened. 


So passing by reference for performance is No, what if we want to return multiple value from a function? We can do that in other ways, for example, we can return an array from the function, or we can pass a parameter object into the function. 


What if sometimes a function is defined and we don't want to change its return type, and we don't want to build parameter object? This is almost like saying 'I just want to use reference'. Well, honestly, sometimes i use reference as well, for convenience and laziness. When i was tempted to use reference, i always check if this prerequisite holds true: 
it is only in a private method of a class. That means, the method  using pass by reference should be hidden within the class. It should not be exposed to others. It must be private only(no protected, no public).


Well, even that, avoid using reference is still a generic rule and we should respect it.