Variables in PHP
Variables in PHP
<?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.
?>
- 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.
- By default, variables are always assigned by value.
- PHP also offers another way to assign values to variables: assign by reference.
- 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.
- Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.
Assign by reference
<?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.
?>
- 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).
- Only named variables may be assigned by reference.
Related concepts
→
Variables in PHP
→
- resource
- NULL
- PHP types
- Syntax: Single quoted
- Syntax: Double quoted
- Syntax: Heredoc syntax
- String: Variable parsing
- Variable parsing: Simple syntax
- Variable parsing: Complex (curly) syntax
- Variables in PHP: Assign by reference
- Predefined Variables
- object: Converting to object
- resource: Converting to resource
- NULL: A variable is considered to be null if