What is variable scope and its type ?

Scope of the variables : 

  • Variables are declared any where in the program .
  • The scope of the programs can be termed as the part of the program where the variable could be declared .
  • Basically in php there are 3 type variables scope .
    1. Local scope
    2. Global Scope 
    3. Static Scope  
   Local Scope : 
  • In this case , the variables are declared with in the function and can be access with in the function only can be termed as the local scope .
  • The function can be termed  as the small piece of task that can be performed when it is called .
<?php

function local_scope()
{
   $ls=20; //local variable
   echo “Local scope variable is   “.$ls;
}
local_scope(); //Call the function 

?>
Here we have decleared $ls as local variables which can be locally accessible in function  local_scope() 
And produce an out pot as : 
Local scope variable is 20

Global Scope :
  • The variable which is declared out side the function and can be accessible from the outside only such functions are termed as global scope .
  • Note : The global variable can be accessible using the global keyword .
<?php
      $gx=10;  //global variable

function global_scope()
{
   global $gx;  //accessing global variable inside function
   echo “Value of gx inside global_scope = “.$gx;
   echo “<br/>”;
  }

global_scope();

echo “Value of gx outside global_scope = “.$gx;

?>
Here , 
  • $gx is the the global variables but it would not work inside the function until we don’t use the variable global to access the variables inside the function .
  • In the second case , the value of $gx will produce the output outside the function ,
Thus , the output would be 
Value of gx inside global_scope = 10
Value of gx outside global_scope = 10
Static Scope 

The static scope remains unchanged with in the execution if the program .
Lets demonstrate with example 
<?php
function static_scope()
{
  $v=0;
  static $s=0;
  echo “Non static return = $v &nbsp;&nbsp; static returns = $s <br>”;
  $v++;
  $s++;
  
}
static_scope();
static_scope();
static_scope();
static_scope();
?>

Here from above example ,
We have 2 variables $v and $s where $v is simple local variable and  $s is local with static scope

The output is as below :

Non static return v = 0    static returns s = 0
Non static return v = 0    static returns s = 1
Non static return v = 0    static returns s = 2

Non static return v = 0    static returns s = 3 

So , you can see that after printing each  time the value of v remains 0 where as value of s increases by 1 in each call .
This is because the local scope looses its value for each call where as static scope retains its value in each time (call) .

Leave a Reply

Your email address will not be published.Required fields are marked *