What is variable?
Variable is a reference(handle) to place in the memory where something is stored. In PHP in variables you can store numbers(integer, float, etc), boolean data(true,false), text, binary data, objects, references, resources, even variables, PHP code (we'll get on that later).
Variable scope
When you define a variable, outside a function, the scope of the variable is global. That means it can be accessed from the included or required files as well. Example:
<?php
$t=1;
include("data.inc.php"); //The variable $t will be accessible in data.inc.php
?>
However:
<?php
$t=1;
test();
function test()
{
echo $t; //not defined, outputs nothing.
}
?>
Global and superglobal variables
Variables that are defined outside a function are automatically global. To access the global variables in a function you must declare them with the global keyword or use the $GLOBALS array:
<?php
$t=1;
function test()
{
global $t;
echo $t; //outputs 1
echo $GLOBALS['t']; //outputs 1
}
?>
There are also superglobal variables. Superglobal variables are predefined reserved variables and are global in every scope. You need not to declare them with the global keyword in a function.
List of superglobal variables:
$GLOBALS; // References all variables available in global scope
$_SERVER; // Server and execution environment information
$_GET; // HTTP GET variables
$_POST; // HTTP POST variables
$_FILES; // HTTP File Upload variables
$_REQUEST; // HTTP Request variables
$_SESSION; // Session variables
$_ENV; // Environment variables
$_COOKIE; // HTTP Cookies
$php_errormsg; // The previous error message
$HTTP_RAW_POST_DATA; // Raw POST data
$http_response_header; // HTTP response headers
$argc; // The number of arguments passed to script
$argv; // Array of arguments passed to script
To view the contents of this array use the function print_r()
Other variables
If register_globals is enabled, variables can be declared externally. This poses major security risk and register_globals should be disabled.
Previous tutorial: Your first PHP page
Next tutorial: PHP arrays