PHP Variables

A variable is nothing more than a name given to a particular area in memory that stores a value created by a PHP script. All variables within PHP are preceded by a '$' sign and must then either start with a letter or underscore. Only letters, numbers and underscores are allowed in variable names. Unlike some languages, for example C#, PHP is a loosely typed language, which means that when a variable is declared, a datatype does not have to be assigned. A variable is automatically converted to the correct datatype depending on the value that is assigned to it.

Below are some examples of variable declarations.

$a; // A variable named 'a' that has not been initalised with a value.
$b = 10; // A variable with the name 'b' that has been assigned an integer value of 10.
$c = 20.54; // A variable with the name 'c' that has been assigned the decimal number 20.54.
$d = "Hello world"; // A variable with the name 'd' that has been assigned the string 'Hello world'.
$e = new DateTime(); // A date time variable named 'e' initialised with the current date and time.

Variable Scope

Variables in PHP can be defined anywhere within a script. The scope of a variable refers to the area of a script that it can be used. Variable scope can either be local, global or static.

Variables with a global scope are those that are defined outside of a function and can only be accessed outside any functions that are defined within the script, however, to get round this, the 'global' key word can be used, followed by the variable names, to make them available within a function. To bring the variables defined above into a function, the global command would look as follows:

function exampleFunction()
{
   global $a, $b, $c, $d, $e;
}

Variables with a local scope are those that are defined within a function and are only accessible from within the function that they are defined.

Usually, when a function has finished executing, all local variables and their contents are destroyed. If however, the contents of a local variable needs to be preserved for the next time that the function is called, then the 'static' keyword can be used when defining it.

function exampleFunction()
{
   static $f = 0;
}