PHP Variable Scope


In PHP, variables can be declared anywhere in the script. The Scope of a variable can be defined as the range of availability of a variable to the program or script code in which it is declared. PHP has three different variables scopes :

local 
global 
static 

local Scope : 

A variable declared within a function has a local scope and can only be referenced within that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function. Example :
<?php
  function myFunc() {
    $myvar = 2000;
    echo "The value of myvar (within the function) : " . $myvar . "<br/>"; 
  }

  myFunc();
  echo "Value of myvar (outside the function) : " . $myvar; 
?>
Output :

The value of myvar (within the function) : 2000
Value of myvar (outside the function) :

The above example shown an error message because in last line of the code try to access the local variable $myvar.


global Scope :

A variable declared outside a function has a global scope and can be accessed outside of a function.Example :
<?php
  $myvar = 1000;
    function myFunc() {
    echo "The value of myvar (within the function) : " . $myvar . "<br/>"; 
  }

  myFunc();
  echo "Value of myvar (outside the function) : " . $myvar; 
?>
Output :

The value of myvar (within the function) :
Value of myvar (outside the function) : 1000

As we can see in the above example the last line of the script will print the $myvar variable but inside the function the $myvar variable shows an error message. To access the global variable inside the function, needs to use the keyword global in front of the variable we want to access. Example :
<?php
  $myvar = 1000;
    
  function myFunc() {
    global $myvar;
    echo "The value of myvar (within the function) : " . $myvar . "<br/>"; 
  }

  myFunc();
  echo "Value of myvar (outside the function) : " . $myvar; 
?>
Output :

The value of myvar (within the function) : 1000
Value of myvar (outside the function) : 1000


static Scope:

Generally the variables declared inside the functions are destroyed or deleted when function ends. However sometimes we need those variables for some reason. So to this we have to use the keyword static when defining the variable. Example :
<?php
    
  function myFunc() {
    static $myvar = 1;
    echo $myvar . "<br/>";
    $myvar++;
  }

  myFunc();
  myFunc();
  myFunc();

?>
Output :

1
2
3

As we can see in the above example each time the function is called, that variable will still have the information it contained from the last time the function was called and the variable is still local to the function.

Next Topic :