PHP: Variable scope

This entry is part 7 of 54 in the series PHP Tutorial

The scope of a variable is the context within which it is defined.

Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

$a = 1; /* global scope */ 

function test()
    echo $a; /* reference to local scope variable */ 


If you type the code into a good IDE such as phpStorm, you will receive a complain from the editor saying that $a is an undefined variable.

The above script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope.

You may notice that this is different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition.

Series Navigation<< PHP: Variables are case sensitive
PHP: Static variable >>