How to Declare Global Variables in PHP
Like most computer languages, PHP comes with a concept of local and global variables. While local variables are defined within a function and dropped from memory after the function ends, global variables remain in place and can be accessed by any part of the program. However, they require some special syntax to use.
Instructions
-
-
1
Type the following into any text editor to define a simple PHP script with a sample function:
<?
function decrement() {
}
decrement();
print "Current value is ";
?>
-
2
Declare a variable at the top of the script by adding the following line immediately after the "<?":
$aValue = 10;
In addition, at "$aValue" to the print line in your script so that it reads:
print "Current value is $aValue";
By not putting it within any identifiable function, this variable automatically becomes a global variable. However, there is one extra step that must be written to use it within a function.
-
-
3
Add the following line with the brackets of the "function decrement" to declare it global:
function decrement() {
GLOBAL $aValue;
return $aValue--;
}
The GLOBAL keyword lets PHP know that it should not declare a new variable with the same name, but should continue using the higher level variable.
-
1