PHP Variable Scope

Variable scope is known as its boundary within which it can be visible or accessed from code. Variable code is classified into two types. These are,

  1. Local scope
  2. Global scope

Since scope restricts variable usage within its boundary, if we use a variable outside its scope it will cause PHP error Undefined Variable.

php_variable_scope

Local Scope:

Local scope is a restricted boundary of a variable within which code block it is declared. That block can be something like function, class or any conditional span. The variable within this limited local scope is known as the local variable of the code block.

The following code block shows a PHP function. We have declared a variable $count inside this function. This variable is said to be a local variable of this function and it is in the local scope of the function block.

<?php
function calculate_count() {
$count = 5;
//will print 5; the value of local variable
echo $count++; 
}
?>

Global scope:

As its name, the global scope provides widespread access to the variable declared in this scope. Variables in global scope can be accessed from anywhere from outside a function or class independent of its boundary.

PHP global variables can be defined by using global keyword. If we want to use global variables inside a function, we have to prefix the global keyword with the variable. The following code shows a code block to learn how to use global keyword with a PHP variable to declared it as a global variable.

<?php
$count = 0;
function calculate_count() {
	global $count;
	// will print 0 and increment global variable
	echo $count++ . "<br/>"; 
}
calculate_count();
echo $count;
?>

PHP has a predefined superglobal variable called $GLOBALS. We can use this array variable to add array of PHP variables in a global scope.

Let us change the above example with global keyword by using $GLOBALS superglobal to access the variable in global scope.

<?php
$count = 0;
function calculate_count() {
// will print 0 and increment global variable declared outside function
echo $GLOBALS["count"]++ . "<br/>"; 
}
calculate_count();
echo $count;
?>

This PHP code tutorial was published on April 12, 2013.

↑ Back to Top