Is there any differents between $GLOBALS[“test”] a

2019-06-08 05:37发布

问题:

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']?

回答1:

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.



回答2:

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.


标签: php global