Scope

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

Displays:

42

0

42

 

 

The $GLOBALS[ ] array also stores global variables, using the name of the variable as the index:

Displays:

42

Local Scope

A locally scoped variable is only valid within the block of code in which it has been declared.

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

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

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:
$myVar inside function is: .
Locally scoped $newVar inside function is: 0.

 
Function USING global variable:
$myVar inside function is: 5.
Locally scoped $newVar inside function is: 25.

 

 

Global $myVar is: 5.
Previously locally scoped $newVar outside the function is: .

Leave a Reply