Introduction
Name of a variable in PHP starts with a $ sign. It is followed by either a letter (A-Z either upper or lowe case) or underscore, and then there may be any number of letters, digits or underscores. Name of variable in PHP is case sensitive.
Syntax
//valid variables $var=10; $VAR="Hello"; //different from $var $marks_1=67; $_val=0; //invalid variables var=10; //not starting with $ $4sqr=16; //not starting with letter/_ $my name="Hello"; //white space not allowed in variable name $my$name="Hello"; //$ character can not be used after first position
A variable is also assigned a value by reference to another variable. To assign value by reference, prefix & sign to name of variable in expression. Changing value of one reflects in value of both
Example
<?php $var1="Hello"; $var2=&$var1; echo $var1 . " " . $var2 . "\n"; $var2="Hi there"; echo $var1 . " " . $var2 . "\n"; ?>
Output
This will produce following result −
Hello Hello Hi there Hi there
Any un-initialized variable carries a default value depending upon the context of use. For example, intger and float variables are 0, boolean is set to FALSE and string variable is an empty string, although newer versions of PHP issue a notice
Following example shows effect of uninitialized variable
Example
<?php $var1=10; $var2=$var1+$var2; echo $var1 . " " . $var2 . "\n"; $x="Hello"; unset($x); var_dump($x); //uninitialized ?>
Output
This will produce following result −
10 10 NULL PHP Notice: Undefined variable: var2 PHP Notice: Undefined variable: x
Following example uninitialized variable in cummulative addition operator−
Example
<?php $sum=$sum+10; var_dump($sum); ?>
Output
This will produce following result −
int(10) PHP Notice: Undefined variable: sum
In following example a default object created from empty value with a warning
Example
<?php $obj->name="XYZ"; var_dump($obj); ?>
Output
This will produce following result −
object(stdClass)#1 (1) { ["name"]=> string(3) "XYZ" } PHP Warning: Creating default object from empty value