0

I started writing a function and added a few globals to it. Then I came on here to read about some issues using global in PHP functions. I understand some of the reasoning why it's bad but don't fully understand it.

An example of one of the links I read PHP global in functions

For example, I have a config.php file that says the name of the user group for all users to be in. I have a functions.php with a function that requires the $user_group variable set in the config file. So I do the following:

function user_group_check($_POST['username']) {
   global $user_group;

   [...code to check if username is in $user_group...]
}

Why would something like this be bad? $user_group is required for the function to even work. So how is using global worse than using `user_group_check($_POST['username'],$user_group) ?

Community
  • 1
  • 1
MarkH
  • 85
  • 1
  • 9
  • Using `global` loading the whole `$user_group;` into memory. Better to avoid unnecessary memory consumption. – eapo Mar 16 '17 at 03:32
  • Wouldn't it consume the same memory by putting it into the function parameters? Or does global automatically load even if the function is not used. – MarkH Mar 16 '17 at 03:34
  • On the link you mentioned there is more answer to your question, like this one: https://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – eapo Mar 16 '17 at 03:40
  • Memory is not the issue. Global variables are bad because they result in "spaghetti code" that is hard to test, hard to debug, and easy to break. It's much better to inject dependencies, rather than using globals. – elixenide Mar 16 '17 at 05:23
  • @EdCottrell since it's in the config file and technically a constant as it does not change throughout the program, does this make it safer to use as a global? The function is actually nested so I would have to pass it multiple times to get to this function. My thought would be that it's more dangerous passing it multiple times than to just declare it as a global. Would be interested in knowing more on this.. – MarkH Mar 16 '17 at 14:04
  • @spl-mark If you're going to use it as a constant, make it a real constant. That is, do `define('USER_GROUP', whatever);`. That way you would know immediately if your code somehow attempted to modify it. But the problem with using a global variable is just that: it's *global* and *variable*, so you can change it -- intentionally or not -- anywhere in your application, with potentially very bad consequences. You might want to read http://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil – elixenide Mar 16 '17 at 14:30
  • @EdCottrell okay, I was used to defining constants as variables sometimes. Bad habit! I'll use define() instead. Thanks! – MarkH Mar 16 '17 at 14:58

0 Answers0