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) {
    ...
}

Avoid using global variables, use the passing variables in parameters approach instead. Depending on the size of your program, the performance may be negligible.

But if you are concerned with performance here are some key things to note about global variable performance with regards to local variables (variables defined within functions.)

  • Incrementing a global variable is 2 times slow than a local var.
  • Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

Also, global variables increase the risk of using wrong values, if they were altered elsewhere inside your code.