The advantage / disadvantage between global variables and function parameters in PHP?

The memory usage is a paltry concern. It’s much more important that the code be easy to follow and not have… unpredicted… results. Adding global variables is a VERY BAD IDEA from this standpoint, IMO.

If you’re concerned about memory usage, the thing to do is

function doSomething (&$var1, &$var2,..) {
   ...
}

This will pass the variables by reference and not create new copies of them in memory. If you modify them during the execution of the function, those modifications will be reflected when execution returns to the caller.

However, please note that it’s very unusual for even this to be necessary for memory reasons. The usual reason to use by-reference is for the reason I listed above (modifying them for the caller). The way to go is almost always the simple

function doSomething ($var1, $var2) {
    ...
}

Leave a Comment