BasicsVariables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
A valid variable name starts with a letter
(
Tip
See also the Userland Naming Guide. Example #1 Valid and invalid variable names
PHP accepts a sequence of any bytes as a variable name. Variable names that do not follow the above-mentioned naming rules can only be accessed dynamically at runtime. See variable variables for information on how to access them. Example #2 Accessing obscure variable names
The above example will output: bar bar By default, variables are always assigned by value. That is to say, when an expression is assigned 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 '
One important thing to note is that only variables may be assigned by reference.
It is not necessary to declare variables in PHP, however, it is a very
good practice. Accessing an undefined variable will result in an
Example #3 Default value of an uninitialized variable
The above example will output: Warning: Undefined variable $unset_var in ... NULL PHP allows array autovivification (automatic creation of new arrays) from an undefined variable. Appending an element to an undefined variable will create a new array and will not generate a warning. Example #4 Autovivification of an array from an undefined variable
Warning
Relying on the default value of an uninitialized variable is problematic when including one file in another which uses the same variable name. A variable can be destroyed by using the unset language construct. For information on variable-related functions, see the Variable Functions Reference. |