Scope

Scope of a variable is its lifetime in the program.

The region of the program in which it can be accessed.

Function Scope

The scope of a variable inside a function is only limited to the function itself.

Accessing such variable outside of the function results in warning.

Let's look at the following example:

Output:

If we uncomment line 9 of the code, it will result in warning.

A variable can be accessed only inside the function it's defined in.

So a global scope variable (such as $globalScopeVariable) cannot be accessed inside a function.

Let's see another example:

Output:

If we uncomment line 11 a warning will be produced because the variable $localVariable is defined inside a function but it's accessed outside of it.

Scope of if statements

Unlike functions if statements don't limit variables scope.

Let's look at the following example:

Output:

age variable is defined at line 4.

It can be accessed at any line afterwards not only inside the if statement.

If at line 4 true is replaced wtih false, then line 7 will produce warning.

Global variables

Global variables can be accessed in any scope.

Global variables are defined using the global keyword.

Let's compare global and local variables:

Output:

A global variable named $globalVar is defined at line 5.

A local variable named $localVar is defined at line 8.

We can access the global variable outside of the function it was defined in at line 13.

If line 14 is uncommented, it will result in warning due to accessing local variable outside of the function it is defined in.

Static variables

Static variables are used to persist value accross multiple function calls.

Let's compare static variables and ordinary variables.

Output:

In this example the static variable - $a persists it's value accross the multiple calls of testStatic.

On the other hand the variable $b always gets assigned to 0 in the beginning of the function.