Determines when and where a variable can be used.
Can also be thought of as the lifetime or validity of the variable.
4 scope types:
- Global
- Local
- Function Parameters
- Static
Global Scope
- Any variable defined outside of any function
- Can be accessed from any part of the script that is not inside a function
- Use the global keyword to access a global variable from within a function
<?php $myGlobal = 6; //global variable $yourGlobal = 7 ; //global variable echo $myGlobal * $yourGlobal . "<br>"; function multiplyNoGlobal() { //unable to use global variables without using global keyword echo $myGlobal * $yourGlobal . "<br>"; } multiplyNoGlobal(); function multiplyGlobal() { global $myGlobal, $yourGlobal ; //use global variables echo $myGlobal * $yourGlobal . "<br>"; } multiplyGlobal(); ?>
Displays:
42 0 42 |
The $GLOBALS[ ] array also stores global variables, using the name of the variable as the index:
<?php $myGlobal = 6; //global variable $yourGlobal = 7 ; //global variable function globalsArray() { //use $GLOBALS array with global variables as index echo $GLOBALS['myGlobal'] * $GLOBALS['yourGlobal'] . "<br>"; } globalsArray(); ?>
Displays:
42 |
Local Scope
A locally scoped variable is only valid within the block of code in which it has been declared.
<?php $myVar = 6; //global variable function localScope() { //Will display nothing as has no local value echo $myVar . "nothing here<br>"; //assign a value to give local scope $myVar = 42; echo $myVar . "<br>"; } localScope(); //display current scoped variable echo $myVar; ?>
Displays:
nothing here 42 6 |
Function Parameters
Objects passed to a function as arguments to be used within the function.
Only valid within the function.
<?php function parameters($myVar, $yourVar) { echo "The two variables passed in were: " . $myVar . " and ". $yourVar . " "; } $firstVar = "Excellent"; $secondVar = 12 ; parameters($firstVar, $secondVar); ?>
Displays:
The two variables passed in were: Excellent and 12 |
Static Variables
Use static keyword within a function to make the variable retains its previous value.
The variable still remains local to that function and cannot be used outside of the function.
<?php function remembering() { STATIC $myVar = 0; $myVar++; echo "\$myVar is now: " . $myVar . " " ; } remembering(); remembering(); remembering(); remembering(); remembering(); ?>
Displays:
$myVar is now: 1 $myVar is now: 2 $myVar is now: 3 $myVar is now: 4 $myVar is now: 5 |
This example shows a bad function (salmon shaded area) without using the global keyword to use the global variable.
Which is then followed by a good function (lilac shaded area) using the global keyword to use the global variable.
Finally it shows that the local variable within a function is non-existent outside of the function:
Displays:
$myVar in global scope is: 5. Function NOT using global variable: Function USING global variable:
Global $myVar is: 5. |