Variable Scope Examples

Sample 1: Local to a function

A variable is "local" to a function or procedure when it is declared inside a function or procedure. Its value cannot be called from outside the function or procedure where it is declared.

<?
//function with variable local to the function
function function1() {
$test1 = "Hello World!";
return $test1;
}

//output values
echo "value of test1 variable: $test1 <br />";
echo "value of function1: " . function1() ."<br />";
?>

Sample 1 Results:
value of test1 variable:
value of function1: Hello World!

Sample 2: Local to a container, but not a function called from within that container

A variable can be local to one function, procedure or other container, but not be local to another function or procedure called from within that parent container.

<?
//function with variable local to a container,
//but not local to the function called from within that container
$test2 = "Hello World!";

function function2() {
return $test2;
}

$test2a = $test2;

//output variables
echo "value of test2 variable: $test2 <br />";
echo "value of function2: " . function2() ."<br />";
echo "value of test2a variable: $test2a <br />";
?>

Sample 2 Results:
value of test2 variable: Hello World!
value of function2:
value of test2a variable: Hello World!

Sample 3: Global variables available to the whole script

Global variables are specifically defined as to have scope throughout the entire lifetime of the code.

<?
//global variable
global $test3;
$test3 = "Hello World!";

function function3() {
global $test3;
return $test3;
}

//output variables
echo "value of test3 variable: $test3 <br />";
echo "value of function3: " . function3() ."<br />";
?>

Sample 3 Results:

value of test3 variable: Hello World!
value of function3: Hello World!

 

Variable Scope Made Simple