6

It seems some people hate global variables, but if you can explain how to code without them, I'm all ears.

Otherwise, I have a few options and I'm curious which is the best long-term. Consider that I have a variable that won't change for the duration. It's a static global. I can use:

$_SESSION['var'] = constantval;
define('var', constantval);
var = constantval;

and the one I'm really curious about:

function my_constants($which)
{
    switch ($which) {
        case 'var':
            return 'constantval';
    }
}

In that last one, the goal is to keep variable out of global scope to save memory at the sacrifice of some processor cost. Is the memory saved worth the cycles? Is there a noteworthy difference between the various other types of global declaration?

not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34
  • Please make an example about your statement "if you can explain how to code without them" ... you need to tell me WHY to use global vars. – Goikiu Jan 09 '14 at 11:07
  • This question is full of red herrings, the biggest one of which is: if you can hardcode the value of `var` then how exactly is it a *variable*? – Jon Jan 09 '14 at 11:13
  • variables != constants – Salman A Jan 09 '14 at 11:16
  • The $ before the word "var" was an error. I fixed it. – not_a_generic_user Jan 09 '14 at 11:26
  • Goikiu, how do you have an abstracted value instead of hardcoding it throughout various files and functions without global variables? As my example shows, I have a constant value and I need it in many different places. How does one do that without global vars? – not_a_generic_user Jan 09 '14 at 11:27
  • 1
    You should use define for constant values. Not only for readability reasons. Using define for constants is a design statement, saying: This value should not be changed by the application. The internal handling of constants is different in many aspects from variables. They can be translated at a early stage of skript parsing. Remember that a PHP skript is first translated to its AST, then to the IR, before it finally gets compiled. Because PHP - interpreter is a Three - Way- compiler, many things happen while peforming this three parsing steps. – Peter Jan 09 '14 at 11:41
  • E.g. Statements will be converted: echo "This is {$someVar}" will be converted to echo "This is";echo $someVar. constants are replaced with their values. That is not true for variables. – Peter Jan 09 '14 at 11:42

2 Answers2

3

Global variables are not considered a bad practice because of memory usage or processor cost. It's because of the problems that allowing any part of your program to modify them may cause. With the time, it becomes hard to understand which parts of the program read or write to your global variables.

Guilherme Sehn
  • 6,727
  • 18
  • 35
  • While that may be, I don't really see how you can get around it for constants like the example that I gave. I'm open to other ideas, but if I have a constant value such as the path to my graphics files or the maximum number of widgets allowed, where else would I put that information to keep it from being hard-coded? – not_a_generic_user Jan 09 '14 at 11:30
  • 1
    Well, you can use constants without problems. Unlike variables, they are immutable and other portions of your application will not be able to modify it. To not pollute the global constants space, I think using class constants would be appropriate, as Artefacto suggested in his answer in this question: http://stackoverflow.com/questions/6736330/are-php-global-constants-a-good-modern-development-practice – Guilherme Sehn Jan 09 '14 at 11:32
  • So a quick clarification if I may: is the only functional difference between globals and constants, the cleanliness of standards? IE, it make people more comfortable but doesn't really behave much differently otherwise? – not_a_generic_user Jan 09 '14 at 11:43
  • See my comment related to PHP - Three -way parsing above. – Peter Jan 09 '14 at 11:59
  • 1
    @not_a_generic_user the difference between constants and global variables is that constants are not mutable, so you can't modify its value once it is set for the first time. Today you certainly know that you won't modify a global variable that is meant to store a constant information in your code, but you should take in account that some day other people may do maintenance in this code or you might forget about this in the future, and taking the right design decisions at this point will make your code less fragile. – Guilherme Sehn Jan 09 '14 at 12:53
  • @GuilhermeSehn, very good point. So really the reason people "hate globals" is because you should be using contstants (at least for values that don't change) – not_a_generic_user Jan 10 '14 at 09:27
  • I've marked yours as the answer, but I want to point out this other stackoverflow question that gave some very good information about the difference between const and define: http://stackoverflow.com/questions/2447791/define-vs-const – not_a_generic_user Jan 10 '14 at 09:31
0

Alternatives to globals (singetons). It will give you a fine grained access control: E.g.:

 class ConfigParamSingelton {
     private var $value;
     private static $mInstance = null;

     public function getValue() { 
         return $this->value;
     }

     public function getInstance() {
         if(self::$mInstance == null) {
            self::$mInstance = new ConfigParamSingelton();
         }
         return self::$mInstance;
     }

So now you can either:

     protected function setValue($val) { // is immuteable by clients of the object
          $this->value = $val;
     }

or

     public function setValue($val) {// is muteable
          $this->value = $val;
     }

Well, this are singletons. You don't need globals in this case.

Peter
  • 1,769
  • 1
  • 14
  • 18
  • Though Singeltons are also considered bad practics. Symfony2 provides a CDI - Container therefore. – Peter Jan 09 '14 at 11:56