Variables in PHP are represented by a dollar sign followed by the name of
the variable. The variable name is case-sensitive, so $myvar
is different from $myVar.
A valid variable name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores.
Example :
<?php
$myvar = "Hello";
// valid
$yourVar_is-123 = "World"; // valid
$123ImHere = "Something"; //
invalid, starts with number
?>
Variable Scope
The scope of a variable is the context within which it is defined. Basically
you can not access a variable which is defined in different scope.
The script below will not produce any output because the function Test()
declares no $a variable. The echo
statement looks for a local version of the $a
variable, and it has not been assigned a value within this scope. Depending
on error_reporting value in php.ini
the script below will print nothing or issue an error message.
<?php
$a = 1; // $a is a global variable
function Test()
{
echo $a; // try to print $a, but $a is
not defined here
}
Test();
?>
If you want your global variable (variable defined outside functions) to
be available in function scope you need to use the$global
keyword. The code example below shows how to use the $global
keyword.
<?php
$a = 1; // $a is defined in global scope ...
$b = 2; // $b too
function Sum()
{
global $a, $b; // now $a and $b are available
in Sum()
$b = $a + $b;
}
Sum();
echo $b;
?>
PHP Superglobals
Superglobals are variables that available anywhere in the program code.
They are :
You usually won't need the last three superglobals in your script.