PHP Variables Scope

The scope of a variable is decribe as its range in the program under which it can be accessed.

The scope of a variable is the part of the program within which it is defined and can be accessed.

Type of Variables Scope

  • Local variable
  • Global variable
  • Static variable

1. Local variable

The variables that are declared within a function are called local variables for that function and it accesible only inside this function.

Example :

<?php  
    function localScope()  
    {  
        $num =50;  //local variable and it accessible only inside the function
        echo "Local variable declared inside this function is: ". $num;  
    }  
    localScope();  
?>

OUTPUT

Local variable declared inside this function is: 50

2. Global variable

The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program.

Example :

<?php  
    $name = "John Doe"; // Global Variable Declaration
    function local_scope_function()  
    {  
        global $name;  
        echo "Variable inside the function: ". $name;  
        echo "</br>";  
    }  
    local_scope_function();  
    echo "Variable outside the function: ". $name;  
?>

OUTPUT

Variable inside the function: John Doe
Variable outside the function: John Doe

3. Static variable

Generally in PHP, when a function is completed/executed, all of its variables are deleted and it completes its execution and memory is freed.

we use the static keyword when you first declare the variable:

Example :

<?php
function myFunction() {
  static $x = 2;
  echo $x;
  $x++;
}

myFunction();
myFunction();
myFunction();
?>

OUTPUT

234