tags:

views:

57

answers:

2

can any one please let me know the basic differences between

$GLOBALS["test"] and global $test

and, will it make sense that, if i use $GLOBALS["test"] instead of $_SESSION['test']?

+3  A: 

and, will it make sense that, if i use $GLOBALS["test"] instead of $_SESSION['test']?

No, session is different thing from a variable that is available globally.

$GLOBALS

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

http://php.net/manual/en/reserved.variables.globals.php

Explanation:

$GLOBALS is an associative array available throughout your script, there is no need to use global $test

Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

Sarfraz
throughout your script:- means, "the current page"...right?
VAC-Prabhu
@PHP-Prabhu: any php page actually. For example `$_POST`, `$_GET`, etc are super global arrays available any time you want :)
Sarfraz
hi Sarfraz, many thanks..
VAC-Prabhu
@PHP-Prabhu: You are welcome :)
Sarfraz
A: 

There is no difference between $GLOBALS["test"] and global $test. Both are pure evil and shouldn't be used.

Why are they evil?

  1. Suddenly your code becomes depended on some outer environment, its portability falls head over heels. It requires some variable defined somewhere, nobody know where, with some value, nobody know what's the proper value.
  2. Imagine that $test is supposed to store an information about something, let's say: number of balls. Everything is fine until there is such a variable and it store what it's suppose to store. However what happen if you decide to delete that variable or use it for other purpose? Bah, fatal errors pop out of nowhere! You don't know what's going on, everything worked fine, you just change a variable's value and everything is falling apart.
Crozin
you must be confusing it with register globals thereby declaring them evil.
Web Logic
I know what the register_globals is and what the global variable is. Both things are evil.
Crozin
Care explaining why exactly is it "evil"
Akay
I've updated my answer.
Crozin