Tuesday, 31 January 2017

TYPES OF VARIABLES IN PHP

Variable is a name of memory location used to store some data. In PHP, no need to provide datatypes at the time of variable declaration because PHP is loosely typed language. Variable names start with ‘$’ symbol. The different types of variables in PHP are –

1. Local Variable – Variable declaration within the function comes under local variable. Local variable of a function cannot be accessed from another function.

Example –
<?php
function fun1()
{
          $x=123;
}
function fun2()
{
          echo "Scott";
          echo $x; // local to fun1()
}
fun1();
fun2();
?>

Output –
Scott
Notice: Undefined variable: x in C:\Users\om\workspace\PhpProjec\first.php on line 9


2. Global Variable – Variable declaration outside of all functions come under global variables. Global variables can be accessed from any function within the script.

Example –
<?php
$x=100;
function fun1()
{
          echo $x; // this cannot access global variable directly through function
          echo $GLOBALS['x'];
}
fun1();
?>

Output –
Notice: Undefined variable: x in C:\Users\om\workspace\PhpProjec\first.php on line 5
100

Note – We cannot access global variables directly from functions. We can access global variable by using $GLOBALS keyword from function


3. Variable Variables – If we assign a variable name as the value of another variable then it comes under variable variables.

Example –
<?php
$x=100;
$y="x";
echo $$y;
?>

Output –
100


4. Static Variable – Static variable can remember previous value. We can assign value only once into static variables.

Example –
<?php
function fun1()
{
          //$x=100;  // Output would have been 101 101 101
          static $x=100;
          $x++;
          echo "$x ";
}
fun1();
fun1();
fun1();
?>

Output –
101 102 103


5.  Reference Variable – It is an alias name of a variable. Both refers the value of same address location.

Example –
<?php
$x=100;
$y=&$x;
echo $y." ";
$x=123;
echo $y;
?>

Output –
100 123


6. Super Global Variables – PHP supports number of super global variables. These variables we can access from any web page in application. All super global variables are array datatypes. Some of them are –
          $_GET
          $_POST
          $_REQUEST
          $_COOKIE
          $_SERVER
          $_SESSION
          $_FILES
          $_ENV

No comments:

Post a Comment