Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - performance and memory issue with global variables

Hypothetical situation: I'm running a complex site in php, and i use a lot of global variables.

i could store the variables in an existing global scope, say $_REQUEST['userInfo'], $_REQUEST['foo'], and $_REQUEST['bar'] etc. and put a lot of different things into the request scope (which would be appropriate use, as these data refer to the request itself).

or

i could keep using lines like global $userInfo, $foo, $bar; in most of my functions.

is there a performance hit, or a difference in memory usage for either solution?

one is a little easier to type... so is there a best-practices guideline?

like image 222
changokun Avatar asked May 09 '26 22:05

changokun


2 Answers

Your global variables are already accessible in $GLOBALS['foo'], $GLOBALS['bar'] etc. This is a clearer indication inside function scope that they come from the global scope than using the global keyword. Should not affect performance in any meaningful way.

Many will tell you that best practice is to avoid global variables in the first place and instead pass variables through function calls and object constructors.

like image 150
Michael Berkowski Avatar answered May 11 '26 11:05

Michael Berkowski


Both are pretty bad. I would suggest using a singleton, or static classes.

As for memory uses, there would be no noticable difference.

like image 37
TJHeuvel Avatar answered May 11 '26 11:05

TJHeuvel