Variable Scope

Scope can be defined as the visibility of a variable throughout the program where it can be used or referenced. Three PHP variable scopes are as listed below:

  1. Local
  2. Global
  3. Static

1.  Local Variables

The variables whose scope or visibility is limited within the function or module, are referred as local variables. Either they can be declared inside the method or passed as an argument.

EXAMPLE : USING LOCAL VARIABLES
<?php
			$a = 5;
			function funScope(){               // defining function funScope()
      $a = 20;        		 // Local Variable
      echo “Value inside the method = ”.$a;		// printing variable $a
}
funScope();		// calling function funScope()
echo “<br>Value outside the method = ”.$a;	
/* 
$a with value 20 is out of scope here and will print value 5 which is assigned outside the function.   
*/
		?>

                        OUTPUT

                        Value inside the method = 20

                        Value outside the method = 5

2. Global Variables

The variables which are accessible throughout the program are known as Global Variables. These variables must be declared outside the function in a way the other variables are declared. There are two methods of accessing global variables in PHP.

  • Using global keyword
  • Using array GLOBALS[var_name] where var_name is the name of a variable.
EXAMPLE 5 : USING GLOBAL VARIABLES
<?php
		// Declaration of global variables
		$name = “PHP Global Variable”;
		$x = 10;
		$y = 20;	
		function funGlobalScope(){
			global $name;		// Using global keyword
			// Using GLOBALS[var_name] array
			$GLOBALS[‘x’] = $GLOBALS[‘x’] * $GLOBALS[‘y’];
			echo $name;
			echo “<br>Multiplication of global variables = ”.$GLOBALS[‘x’];
}
funGlobalScope();
?>

OUTPUT

PHP Global Variable

Multiplication of global variables = 200           

2. Static Variables

The lifetime of a variable is limited to the block in which it is declared but in some cases we want to preserve the value of the variable throughout the execution of the program, Static Variables serve the same purpose. The variables are declared with a static keyword. The syntax looks like:

EXAMPLE 6 : USING STATIC VARIABLES
<?php
		function funSaticScope(){
			static $num = 0;		// Using static keyword
			$num++;
			echo “<br>”.$num;
}
funSaticScope();
            funSaticScope();
funSaticScope();
?>

OUTPUT

1

2

3

Function funSaticScope() is called three times but the variable $num is initialized only once and is retaining its old value each time it is called.