Rate Us :

Share with Friends :


Types of variables in PHP :

A variable is the name of memory location used to store values at the time of program execution. PHP is loosely typed language that's why we can create variables without data types.

Types of variables :

Local variable :

Variable declaration within the function comes under local variable declaration. Local variables can be accessed within the function where we declared it but we cannot access it from outside the function.

Example :

<?php error_reporting(E_ALL); function fn1() { $x = 100; } function fn2() { echo $x; } fn1(); fn2(); ?>

Output :

Notice : Undefined variable : x

Global variable :

Variable declaration in Global location means outside all functions. Global variable can be accessed from any function within the script. By default, we cannot access Global variables, use "global" keyword to redeclare the variable within the function as Global variable.

Example :

<?php error_reporting(E_ALL); $x = 100; function fn1() { $x = 111; echo $x; echo "<br>"; } function fn2() { global $x; echo $x; echo "<br>"; } fn1(); echo $x; echo "<br>"; fn2(); echo $x; echo "<br>"; ?>

Output :

111 100 100 100

variables_variable :

If we put variable name as the value of another variable then it is a variables_variable.

Example :

<?php $x = "Man"; $y = 'x'; echo $$y; ?>

Output :


Static variables :

Static variables can maintain the previous values. We can assign the value only one time into static variable.

Example :

<?php function fn1() { static $x = 100; $x++; echo $x; } fn1(); echo "<br>"; fn1(); echo "<br>"; fn1(); ?>

Output :

101 102 103

Reference variables :

It refers the value of another variable. Actual variable and reference variables refer the value of same address location.

Example :

<?php $x = 100; $y = &$x; $y = 200; echo $x; ?>

Output :


Super Global variables :

PHP is providing number of Super Global variables. We can access this Super Global variables from any location (from any web page) within the project.

Different types of Super Global variables are available. Those are $_GET, $_POST, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE, $_FILES, $_END. All Super Global variables are of array types.