简体   繁体   中英

What is the most efficient way of handling global variables in PHP?

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?

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.

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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM