Core PHP

Variable Scope

The scope of a variable in PHP can have few different variations: local, global or static. Local variables have their scope contained within a small code block. In PHP, the only local variables are those that are declared within a function. Anything variable that is not declared within a function is global, which means that it can be accessed everywhere. Static variables are declared within a function but can be accessed within the function every time that the function is called.

Local variables differ from static variables in that local variables start their lifetime during a function call and end it when the execution exits the function. Static variables an only be acccessed within the function, However, static variables continue their lifetimes during the entire program once the function is called the first time.

The program below begins with four function definitions that are executed when they are called in the code below them. The code begins executing at the line

$Xoax = "global";

where the only global variable is declared and initialized. Then the function SetToLocal() is called, but it does not access the global variable, only the local one. After the call, we output the value of the gloabl variable to confirm this. Then UpdateStatic() is called twice, which declares, initializes, and appends an asterisk to the string that it holds each time it is called. Again, we output the global variable to verify that it has not changed. So far, we have had three variables with the same name: one global, one local, and one static.

Next, we call AccessGlobal1() and AccessGlobal2() and output the value of the global variable after each call. These two functions demonstrate two equivalent ways to access a global variable. The first function accesses the global variable via the global specifier and appends an exclamation point. The second accesses the global variable via the $GLOBALS arrays and appends a question mark.

VariableScope.php

<?php

function SetToLocal() {
	$Xoax = "local";
	echo "Local \$Xoax = " . $Xoax . "<br />";
}

function UpdateStatic() {
	static $Xoax = "static";
	$Xoax .= "*";
	echo "Static \$Xoax = " . $Xoax . "<br />";
}

function AccessGlobal1() {
	global $Xoax;
	$Xoax .= "!";
}

function AccessGlobal2() {
	$GLOBALS[Xoax] .= "?";
}


$Xoax = "global";

echo "Initially, Global \$Xoax = " . $Xoax . "<br />";
SetToLocal();
echo "After SetToLocal() is called, Global \$Xoax = " . $Xoax . "<br />";
UpdateStatic();
UpdateStatic();
echo "After UpdateStatic() is called, Global \$Xoax = " . $Xoax . "<br />";
AccessGlobal1();
echo "After AccessGlobal1() is called, Global \$Xoax = " . $Xoax . "<br />";
AccessGlobal2();
echo "After AccessGlobal2() is called, Global \$Xoax = " . $Xoax . "<br />";

?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.