Variables are those which is used to store the information. They act like a container.
It start with ‘$’ this sign and follow by name of the variable.
Variable name should either start with Underscore or some letter but I can never start with a number.
Example:
1 2 3 4 5 6 7 8 9 | <?php $a = 5; echo $a; $price = 66.5; echo "Price is ".$price; $name="Ram"; echo "My Name is $name"; ?> |
Result:
5 Price is 66.5 My Name is Ram
Explanation: $a stored a numeric value $price hold fractional value and $name hold a string value.
Now moving further, PHP has three different types of variable scopes in a program. The three are :
Global Variable in PHP
The variable which is declared outside the function then is called Global variable.
This variable can be access outside the particular function.
Example:
1 2 3 4 5 6 7 8 9 10 | <!--?php $data = 12.55; function getIt() { global $data; echo "[" . $data . "]"; } getIt(); ?--> |
Result:
[12.55]
Local Variables in PHP
The variable which is declared inside the function then is called Local variable. This variable can be only access inside the function.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <title>Local variable in PHP</title> </head> <body> <?php function printIt() { $a = 25; echo "value of a= " . $a; } printIt(); echo "value of a= " . $a; ?> </body> </html> |
Output
1 2 3 | value of x= 25 Notice: Undefined variable: a in C:\xampp\htdocs\ZZZPhpProject2\local.php on line 15 value of x= |
Explanation: The variable was declared inside the function will not be call up outside the function, it can only be called at inside the function. While calling the local variable outside the function will give some error.
Static variable in PHP
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html> <body> <?php function show() { static $i = 0; $j=0; $i++;//incrementing static variable $j++;//incrementing local variable echo "value of i=".$i." j= ".$j."<br/>"; } show(); show(); show(); ?> </body> </html> |
Output
1 2 3 | value of i=1 j= 1 value of i=2 j= 1 value of i=3 j= 1 |
Explanation: Here i is static variable and j is local variable.
Static variable initialized once and on each function call it is getting incremented.