Variable Scope

Variable Scope.

Scope describes the lifetime of the variable. This means that the scope of a variable is the block of code in an entire program where the variable is declared, used, and can be modified. In PHP there are three types of scope.

  • Local Variable.
  • Global Variable.
  • Static Variable.

Local Scope.

Local scopes are limited to a specific function. Once we declared any variable within the function that variable cannot be accessed outside the function.

Local Scope Example.

<?php
    function localVarScope()  
    {  
        $var = "Hello PHP";  //local variable  
        echo "This is an example of local variable scope:". $var;  
    }  
    localVarScope();  
?>

Output :

This is an example of local variable scope: Hello PHP

Global Scope.

The variable that is used anywhere in a program is known as the global variable. To access the global variable inside the function, In PHP we can use the GLOBAL keyword before the variable. However, we can directly access these variables outside the function.

Global Scope Example.

<?php  
    $name = "PHPForever";
    function globalVarScpe()  
    {  
        global $name;  
        echo "Variable inside the function: ". $name;  
        echo "</br>";  
    }  
    globalVarScpe();  
    echo "Variable outside the function: ". $name;  
?>

Output :

Variable inside the function: PHPforever;
Variable inside the function: PHPforever;

Static Scope.

It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we need to store a variable even after the completion of function execution. This keyword is used to store a variable after the completion of function execution.

Static Scope Example.

<?php
function staticScope(){

    static $static_var = 1;
    $non_static_var = 1;
    $static_var ++;
    $non_static_var++;
    echo "Static: " . $static_var . "</br>";
    echo "Non-static: " . $non_static_var . "</br>";
}
// first call
staticScope();
// second call
staticScope();
?>

Output :

Static: 2</br>
Non-static: 2</br>
Static: 3</br>
Non-static: 2</br>

Previous: PHP Variables                                                                                                                   Next: Data Types.

Back to top button