Global variables should be used sparingly, since it's easy to
accidentally modify a variable by mistake. This kind of error can be very
difficult to locate. Additionally, when we discuss functions in detail, you'll
learn that you can send in values to functions when you call them and get values
returned from them when they're done. That all boils down to the fact that you
really don't have to use global variables.
If you want to use a variable in a specific function without losing the value
each time the function ends, but you don't want to use a global variable, you
would use a static variable.
PHP uses special variables called super
globals to provide information about the PHP script's environment. These
variables don't need to be declared as global; they are automatically available
and provide important information beyond the script's environment, such as
values from a user input.
Variable array name
|
Contents
|
---|---|
$GLOBALS
|
Contains any global variables that are accessible for the local
script. The variable names are used to select which part of the array to
access.
|
$_SERVER
|
Contains information about the web server
environment.
|
$_GET
|
Contains information from GET requests (a form
submission).
|
$_POST
|
Contains information from POST requests (another type
of form submission).
|
$_COOKIE
|
Contains inform from HTTP cookies.
|
$_FILES
|
Contains information from POST file
uploads.
|
$_ENV
|
Contains information about the environment (Windows or
Mac).
|
$_REQUEST
|
Contains information from user inputs. These values should not
be trusted.
|
$_SESSION
|
Contains information from any variables registered in a
session.
|
An example of a super global is PHP_SELF. This
variable contains the name of the running script and is part of the
$_SERVER array.
<?php echo $_SERVER["PHP_SELF"]; ?>
This variable is especially useful, as it can be used to call
the current script again when processing a form. Super global variables provide
a convenient way to access information about a script's environment from server
settings to user inputted data. Now that you've got a handle on variables and
scope, we can talk about what types of information variables hold.