PHP Variables Summary

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
NoteFor our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).
<?php
$var 
'Bob';$Var 'Joe';
echo 
"$var$Var";      // outputs "Bob, Joe"
$4site 'not yet';     // invalid; starts with a number$_4site 'not yet';    // valid; starts with an underscore$täyte 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.?>
By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.
PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php
$foo 
'Bob';              // Assign the value 'Bob' to $foo$bar = &$foo;              // Reference $foo via $bar.$bar "My name is $bar";  // Alter $bar...echo $bar;
echo 
$foo;                 // $foo is altered too.?>
One important thing to note is that only named variables may be assigned by reference.
<?php
$foo 
25;$bar = &$foo;      // This is a valid assignment.$bar = &(24 7);  // Invalid; references an unnamed expression.
function test()
{
   return 
25;
}
$bar = &test();    // Invalid.?>
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
Example #1 Default values of uninitialized variables
<?php// Unset AND unreferenced (no use context) variable; outputs NULLvar_dump($unset_var);
// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)echo($unset_bool "true\n" "false\n");
// String usage; outputs 'string(3) "abc"'$unset_str .= 'abc';var_dump($unset_str);
// Integer usage; outputs 'int(25)'$unset_int += 25// 0 + 25 => 25var_dump($unset_int);
// Float/double usage; outputs 'float(1.25)'$unset_float += 1.25;var_dump($unset_float);
// Array usage; outputs array(1) {  [3]=>  string(3) "def" }$unset_arr[3] = "def"// array() + array(3 => "def") => array(3 => "def")var_dump($unset_arr);
// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';var_dump($unset_obj);?>

Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
<?php
$a 
1;
include 
'b.inc';?>
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
<?php
$a 
1/* global scope */
function test()
{
    echo 
$a/* reference to local scope variable */ }
test();?>
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword ¶

First, an example use of global:
Example #1 Using global
<?php
$a 
1;$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;
}
Sum();
echo 
$b;?>
The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
Example #2 Using $GLOBALS instead of global
<?php
$a 
1;$b 2;

function 
Sum()
{
    
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo 
$b;?>
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because$GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:
Example #3 Example demonstrating superglobals and scope
<?phpfunction test_global()
{
    
// Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    
global $HTTP_POST_VARS;
   
    echo 
$HTTP_POST_VARS['name'];
   
    
// Superglobals are available in any scope and do
    // not require 'global'. Superglobals are available
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    
echo $_POST['name'];
}
?>
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

Using static variables ¶

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
Example #4 Example demonstrating need for static variables
<?phpfunction test()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>
This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Example #5 Example use of static variables
<?phpfunction test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>
Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Example #6 Static variables with recursive functions
<?phpfunction test()
{
    static 
$count 0;

    
$count++;
    echo 
$count;
    if (
$count 10) {
        
test();
    }
    
$count--;
}
?>
Note:
Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
Example #7 Declaring static variables
<?phpfunction foo(){
    static 
$int 0;          // correct
    
static $int 1+2;        // wrong  (as it is an expression)
    
static $int sqrt(121);  // wrong  (as it is an expression too)

    
$int++;
    echo 
$int;
}
?>
Note:
Static declarations are resolved in compile-time.

References with global and static variables ¶

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?phpfunction test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}
test_global_ref();var_dump($obj);test_global_noref();var_dump($obj);?>
The above example will output:

NULL
object(stdClass)(0) {
}
A similar behaviour applies to the static statement. References are not stored statically:
<?phpfunction &get_instance_ref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign a reference to the static variable
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign the object to the static variable
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}
$obj1 get_instance_ref();$still_obj1 get_instance_ref();
echo 
"\n";$obj2 get_instance_noref();$still_obj2 get_instance_noref();?>
The above example will output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
<?php
$a 
'hello';?>
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example,hello, can be used as the name of a variable by using two dollar signs. i.e.
<?php$$a 'world';?>
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and$hello with contents "world". Therefore, this statement:
<?phpecho "$a ${$a}";?>
produces the exact same output as:
<?phpecho "$a $hello";?>
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write$$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as$foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.
Caution
Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.
Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).
Example #1 Variable property example
<?phpclass foo {
    var 
$bar 'I am bar.';
    var 
$arr = array('I am A.''I am B.''I am C.');
    var 
$r   'I am r.';
}
$foo = new foo();$bar 'bar';$baz = array('foo''bar''baz''quux');
echo 
$foo->$bar "\n";
echo 
$foo->{$baz[1]} . "\n";
$start 'b';$end   'ar';
echo 
$foo->{$start $end} . "\n";
$arr 'arr';
echo 
$foo->{$arr[1]} . "\n";
?>
The above example will output:

I am bar.
I am bar.
I am bar.
I am r.