This is not a theoretical or general question about when to use “pass by reference” vs “pass by value”. Several questions of that type here, and NONE of them answer my very specific question:
In PHP, when passing a database connection resource ID to a function (just a simple procedural function, not any class or anything complicated) does it matter if I pass by reference or by value?
The connection itself does absolutely nothing. It is never changed. So both reference and value work fine.
My question I suppose is to figure out WHY I would pass it by reference. I have old inherited code, and the comments in the code suggest that passing by reference saves memory and speeds up performance. I wonder if this is true?
Btw I am using Postgresql connections, not MySQL.
Thanks!
A database connection is a “resource”. It is usually just a pointer, so it doesn’t matter whether you pass it by value or by reference. Resources behave like objects in this sense.
Passing by reference used to have a significant effect on memory usage in the past. That’s why old code contains so many & operators. But this is no longer necessary. PHP 5 uses copy-on-write semantics for variables, so it doesn’t cost any more memory to pass things by value in most circumstances. Especially if it’s just a pointer like a resource… but this also applies to other types of variables such as string and arrays. (Try passing a 1MB string by value. Memory consumption will NOT go up by 1MB.)