i

PHP Tutorial

Variable Scope

As we have discussed variable scope in 2.1.4 in brief, let us see how the variable scope works with functions.

>Local scope

When a variable is declared within a function, it can only be used inside that function as it has a local scope. You cannot access the variable declared inside a function anywhere in the script outside the function. 

For example:

function numeric()

{

           $num1 = 20; //$num1 has a local scope

           echo “ Number used inside the function is: $num1”;

}

numeric();

echo “ Number outside the function is: $num1”;

?>

In the above php code output will be:

Number used inside the function is: 20

Number outside the function is:

The second statement would not be able to access the variable as it has a local scope and declared inside a function.

>Global scope

When a variable is declared outside a function, it can only be used outside that function as it has a global scope. You cannot access the variable inside a function that is declared anywhere in the script outside the function. 

For example:

$num1 = 20; //$num1 has a global scope

function numeric()

{

           //the variable cannot be accessed inside a function.

           echo “ Number inside the function is: $num1”;

}

numeric();

echo “ Number outside the function is: $num1”;

?>

In the above php code output will be:

Number inside the function is: 

Number outside the function is: 20

The first statement would not be able to access the variable as it has a global scope and declared outside a function.

Global Keyword allows you to access a global variable declared inside the function. So, you can access the values of the variables that are used inside a function anywhere in the script using the global keyword.

For example:

$a = 3;

$b = 4;

function sum()

{

           global $a, $b;

           $b = $a + $b ;

}

sum();

echo $b;

?>

The output of the above-written code will be 7 as the global keyword will get access of the variables outside the function.

Static scope

Whenever you want a function to store the values of its variables, you can use the static keyword as the local variables used inside the function will lose their values once the function is called. But with the static keyword, you can keep the values stored in the variable.

For example:

function static_test()

{

           static $num = 1;

           echo $num;

           $num++;

}

static_test();

static_test();

static_test();

?>

The output of the above code will be as below:

1

2

3

As the static keyword will store the value 1 and when the function is called, it prints one and increments it to 2. Then again the function is called, it prints 2 and increments the value to 3.