Chapter 7. Variables

Table of Contents
Basics
Predefined variables
Variable scope
Variable variables
Variables from outside PHP

Basics

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

  1  
  2 $var = "Bob";
  3 $Var = "Joe";
  4 echo "$var, $Var"; // outputs "Bob, Joe"
  5      

In PHP3, 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 Expressions.

PHP4 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. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.

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:

  1 
  2 <?php
  3 $foo = 'Bob';              // Assign the value 'Bob' to $foo
  4 $bar = &$foo;              // Reference $foo via $bar.
  5 $bar = "My name is $bar";  // Alter $bar...
  6 echo $foo;                 // $foo is altered too.
  7 echo $bar;
  8 ?>
  9      

One important thing to note is that only named variables may be assigned by reference.

  1 
  2 <?php
  3 $foo = 25;
  4 $bar = &$foo;      // This is a valid assignment.
  5 $bar = &(24 * 7);  // Invalid; references an unnamed expression.
  6 
  7 function test() {
  8    return 25;
  9 }
 10 
 11 $bar = &test();    // Invalid.
 12 ?>
 13