A variable is a container for storing information. There are some rules for php variables in php as follow.
- PHP Variables name starts with “$” sign, followed by name
- PHP Variables name starts with a letter or underscore character
- PHP Variables name can not be started with a number
- PHP Variables name can only contain alpha numeric characters and underscores
- PHP Variables names are case sensitive
Variable are printed/output with echo or print statement.
Following are some examples
$alfa = "I am Alfa variable";
echo $alfa;
Above example show output of a string variable, while if you have two variable with numeric value with some arithmetic operator as follow then out will be result of arithmetic opertaion
$a = 5;
$b = 10;
echo $a + $b; // it will output 15
There are 3 types of variable scope
- Global
- Local
- Static
Global:
Variable declared out side a function has a global scope. For details look at following example, $a variable is declared out side the function myAlfa is accessible only outside the function, while inside the function it will not output $a value.
$a = "I am A";
function myAlfa() {
echo $a." inside the function";
}
echo $a." outside the function";
Local:
Variable declared inside a function has a local scope. As in following example $a is declared inside a function myAlfa is only accessible within the the function. It will not output value of $a outside the function, because local variables are destroyed as the function execution completes.
function myAlfa() {
$a = "I am A";
echo $a." inside the function";
}
echo $a." outside the function";
Static:
Some times we need the variables even once the function is executed. So here we use static variables. as in following example $a variable is incrementing value on each function call.
function myAlfa() {
static $a = 0;
echo $a;
$a++;
}
myAlfa();
echo "<br>";
myAlfa();
echo "<br>";
myAlfa();
