Press "Enter" to skip to content

What is Local Variable Scope in PHP?

What is Variable Scope in PHP?

The variable scope defines the visibility of variables in PHP programs. In PHP there are three variable scopes. These are given below:

(i) Local Scope
(ii) Global Scope
(iii) Static Scope

What is the Local Variable Scope in PHP?

In PHP, when a variable is declared within a function, that variable will contain local scope. Local variable will be accessed and visible only within that function where that will be declared.

Now we will write a program on the local scope of a variable:

In this program, we will define a function f1. Within the function body, there is a local variable $a with an initialized string “welcome” here, and we will try to access that variable outside the function.

<html>
    <body>
        <?php
function f1()
{
    $a="welcome"; //$a variable has a local scope
    echo $a;
}
f1(); //function calling
echo $a; //error beacuse local variable is accessing outside the function
        ?>
    </body>
</html>

Output

welcome
E_NOTICE : type 8 -- Undefined variable: a -- at line 10

In the above program, the variable $a has a local scope. After executing the program, there will be an error, because variable $a is accessing outside the function.

Here is a PHP program using a local variable within a function with an initialized value.

In this program, we will use a user-defined function f1, and we will declare a local variable $a with initialized to 5 inside the function then we call the function for three times:

<html>
    <body>
        <?php
function f1()
{
    $a=5; //local scope
    $a=$a+1; //increasing value
    echo $a."<br>";
}
f1(); //function calling
f1(); //function calling
f1(); //function calling
        ?>
    </body>
</html>

Output

6
6
6

Here function is calling for three times. Local variable will be initialized for every time for each calling of a function(where the local variable is declared). So the outputs are 6,6 and 6.