Php Variable


The variable in PHP is represented by a dollar-sign followed by the name of the variable. The variable name is case-sensitive. The variable naming rule is a valid variable name that starts with a letter or underscores, followed by any number of letters, numbers, or underscores. Example
<?php
$var='hello';
$Var ='world';
echo $var.''.$Var; // hello world
$4site= 'hi'; // invalid
$_4site ='hi';// valid
?>
There are three types of variables scope. (1) Local (2) Global (3) Static The Static Variable Another important feature of variable scope in the static variable. A static variable exists just in a local function scope, yet it doesn't lose its value when program execution leaves this scope. Simple Example
<?php
function test(){
$a=0;
echo $a;
$a++;
}
test();
test();
test();
//output
//000
?>
This function is quite useless since every time it is called it sets $a to 0 prints "0". The $a++ which increment the variable servers no purpose since as soon as the function exits the $a variable disappears. Example
<?php
function test(){
static $a=0;
echo $a;
$a++;
}
test();
test();
test();
//output
//012
?>
Now every time the test() function is called it will print the value of $a and increment it. The Global Variable In PHP global variable must be declared global inside a function if they are going to be used in that function using global keyword and PHP defined $GLOBALS array. Example
<?php
$a=1;
$b=2;
function sum(){
 Global $a,$b;
 $b=$a+$b;
}
sum();
echo $b;
//output
//3
?>
Declaring $a and $b global within the function, all references to either variable will refer to the global version. A second way to access the variable from the global scope is to use the special PHP-defined $GLOBALS array. Example
<?php
$a=1;
$b=2;
function sum()
{
  $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['B'];
}
sum();
echo $b;
?>