Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

global

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?

like image 253
not_a_generic_user Avatar asked Oct 21 '22 17:10

not_a_generic_user


1 Answers

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.

like image 135
Guilherme Sehn Avatar answered Oct 23 '22 10:10

Guilherme Sehn