Are global variables in PHP considered bad practice? If so, why?

Viewed 39555
function foo () {
    global $var;
    // rest of code
}

In my small PHP projects I usually go the procedural way. I generally have a variable that contains the system configuration, and when I nead to access this variable in a function, I do global $var;.

Is this bad practice?

6 Answers

As:

global $my_global; 
$my_global = 'Transport me between functions';
Equals $GLOBALS['my_global']

is bad practice (Like Wordpress $pagenow)... hmmm

Concider this:

$my-global = 'Transport me between functions';

is PHP error But:

$GLOBALS['my-global'] = 'Transport me between functions';

is NOT error, hypens will not clash with "common" user declared variables, like $pagenow. And Using UPPERCASE indicates a superglobal in use, easy to spot in code, or track with find in files

I use hyphens, if Im lazy to build classes of everything for a single solution, like:

$GLOBALS['PREFIX-MY-GLOBAL'] = 'Transport me ... ';

But In cases of a more wider use, I use ONE globals as array:

$GLOBALS['PREFIX-MY-GLOBAL']['context-something'] = 'Transport me ... ';
$GLOBALS['PREFIX-MY-GLOBAL']['context-something-else']['numbers'][] = 'Transport me ... ';

The latter is for me, good practice on "cola light" objectives or use, instead of clutter with singleton classes each time to "cache" some data. Please make a comment if Im wrong or missing something stupid here...

Related