Variables in PHP | PHP Variables
Variables in PHP :
- Variables in PHP are represented by a dollar sign followed by the name of the variable.
- The variable name is case sensitive. i.e. ($a and $A are two different variables.)
- A valid variable name starts with a letter or underscore, followed by any number of letters, numbers and underscores
Declaration of Variables in PHP :
Syntax : $variable-name = value;
Example:
<?php
$a = ‘Hello’;
$b = 2;
$c = 18.2;
echo “String variable : $a” ,”<br>”;
echo “Integer Variable : $b ” , “<br>”;
echo $c;
?>
Scope of the variable in PHP :
- Variables in PHP can be defined anywhere and scope of the variable is the context within which it is defined.
- For the most part all PHP variables only have a single scope.
- Any variable used inside a function is by default limited to the local function scope.
- Scope of variable can be local, global or static.
Example:
<?php
$var = 1;
function test()
{
$var=500;
echo “Var is (Local Scope) : $var”;
}
test();
echo “<br> Var is (Global Scope) : $var”;
?>
Global Keyword in PHP :
- In PHP global variables 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
$M = 10;
$N = 20;
function sum()
{
$M = 5;
global $M, $N;
$N = $M + $N;
}
sum();
echo $N; //outputs 30
?>
- A second way to access global variables form the global scope is to use the special PHP defined $GLOBALS array.
Example :
<?php
$M = 10;
$N = 50;
function sum()
{
$GLOBALS[‘N’] = $GLOBALS[‘M’] + $GLOBALS[‘N’];
}
sum();
echo $N; //outputs 60
?>
Static Variable in PHP :
- A static variable exists only in a local function scope but it does not lose its value when program execution leaves this scope.
- Example : if you don’t use static keyword output would be : 0 0 0
<?php
function test()
{
static $a=0;
echo $a;
$a++;
}
test();
test();
test();
?>
Variable variables
- Sometimes it is convenient to be able to have variable variable names i.e. a variable name which can be set and used dynamically.
- Here in this code hello can be used as the name of variable by using two dollar signs.
- $a contains “hello” and $hello contains “world”. So both the statement will give same output.
Example:
<?php
$a=”hello”;
$$a=”world” //$hello=”world”;echo “$a ${$a}”;
echo “<br>”;
echo “$a $hello”;
?>