VARIABLE SCOPE IN PHP

There are 3 types of Variable Scope in PHP. They are listed below;

  1. Local Variable
  2. Static Variable
  3. Global Variable.

Local Variable:

                                A local variable is any variable within a function curly brace ’{}’.

For Example;

<?php
function solarexEmpire(){
    $x = 4;
    echo $x;
}
// End of function

//calling of function
solarexEmpire();
?>

$x is a local variable in the example above as it can only be assessed within a function.

Static Variable:

                                A static variable is a variable that retains its value between function curly braces. A static variable is declared by using the word ‘static’ inside a function.

For Example;

<?php
function solarexEmpire(){
    static $x = 4;
    echo $x;
}
// End of function

//calling of function
solarexEmpire();
?>

Global Variable:

                                Global variable is a variable outside a function. It can only be assessed outside a function.

For Example;

<?php
function solarexEmpire(){
    global $x = 4;
    echo $x;
}
// End of function

//calling of function
solarexEmpire();
?>
				OR
$x = 20;
Echo $x; // outcome will be 20.

This concludes our lecture on Variable scope.

Leave a Comment

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