PHP Variable Scope

Scope of variables in PHP

  • The scope is the area or range within which the variable is accessible.
  • The scope of the variables are mainly controlled by the braces “{“
  • In php, a variable can be in any one of the following scope
    1. Super Global Variables
    2. Global Variables
    3. Local Variables

 

Super Global Variables:

  • This type of variables are accessible from anywhere
  • This type of variables are called super global variables.
  • Ex -  $_POST[], $_GET[], $_SEESSION etc.

 

Global Variables:

  • Variables that are accessible within the whole program is called global variable.
  • “global” keyword is used to access global variable in local scope with same variable name.
  • A variable defined outside a function body cannot be referenced within a function.

Example:

<?php

$value = 1; // $value is a global variable

function fun() {

var_dump($value);

}

fun();

?>

Output: NULL.

$value variable is NULL in the fun() function

<?php

$value = 1;

function simple() {

global $value; //global keyword is used to access global variables.

$value = 2; // After this assignment value of global variable will be changed from 1 to 2.

}
echo $value, " ";

simple();

echo $value;

?>


Output: 1 2

 

Local Variables:

  • Variables declared within opening and closing braces are called local variables.
  • Their scope are limited with the opening and closing braces.
  • They are not accessible outside this scope.
  • More power than global variables when accessed within the local scope.
<?php

$value = 4; // $value is global variable here.

function simple() {

$value = 3; //$value is local here

echo $value.” ”; // value of $value will be 3, because in local, power of local variable is greater.

}
simple();

echo $value;

?>


Output: 3 4

Check Page Rank