Variable Scope in PHP

Scope of the variable means extent within which it can be accessed. Based on the scope of the variable it can be defined as local variable or global variable.

Local Variable

If a variable is defined within a function then it can be accessed within that function block. Such variables is known as local variable. The scope of local variable is within the function block in which they are defined and cannot be accessed outside the function.

Example

<?php

function scopeTest()
{
	$i = 10; //local variable
	echo "Local Variable $i"; //Local Variable 10
}

scopeTest();

?>

Global Variable

If a variable is defined outside all the functions then it can be used anywhere in code. Such variables is known as global variable.

Example

<?php

$i = 11; //global variable

function scopeTest()
{
	$i = 10; //local variable
	echo "Local Variable $i"; //Local Variable 10
}

scopeTest();

echo "<br />";
echo "Global Variable $i"; //Global Variable 11

?>

Accessing global variables within a function

All the global variables are stored in super global variable $GLOBALS. $GLOBALS is an associative array. To access a global variable within a function you can pass the variable name as an index to $GLOBALS. Arrays will be covered later. Global variables can also be accessed by using global keyword. Both these methods of accessing global variables are explained next.

Using global keyword

Here is how to use global variables within a function using global keyword.

Example

<?php

$i = 11; //global variable
$j = 12;

function scopeTest()
{
	global $i, $j; //accessing global variable
	echo "Global Variable $i and $j"; //Global Variable 11 and 12
}

scopeTest();

?>

The example is easy to understand.

Using $GLOBALS array

Here's how you you can use $GLOBALS super variable to access global values within functions.

Example

<?php

$i = 11; //global variable
$j = 12; //global variable

function scopeTest()
{
	$i = $GLOBALS['i']; //accessing global variable
        $j = $GLOBALS['j']; 

	echo "Global Variable $i and $j"; //Global Variable 11 and 12
}

scopeTest();

?>