Zend PHP 7 Certification – Functions – Variable Scope

This post covers the Variable Scope section of the Functions chapter when studying for the Zend PHP 7 Certification.

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

For a simple procedural PHP script with no functions, the variables will be defined in the global scope.

Any functions added that declare variables within them, the variables will be considered to be the local scope.

A single scope spans included and required files, as seen in the below example.

<?php
$a = 1;
include 'b.php';

Here the variable $a will be available in the b.php file.

In the second example below, $a is defined in the global scope and inside the function, $a is echoed in the local scope, therefore produces no output.

<?php
$a = 1; /* global scope */ 

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

test(); // No output

To solve this, the global keyword can be used to define variables in the global scope.

<?php
$a = 1;
$b = 2;

function Sum() {
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b; // Outputs: 3

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.

<?php
$a = 1;
$b = 2;

function Sum() {
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
} 

Sum();
echo $b; // Outputs: 3

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:

<?php
function test() {
    $a = 0;
    echo $a;
    $a++;
}

This will only output 0 as straight after $a is incremented by one, the function exits and the $a variable disappears. The example below demonstrates declaring a variable static.

<?php
function test() {
    static $a = 0;
    echo $a;
    $a++;
}

test(); // Outputs: 0
test(); // Outputs: 1

// Static variables can also be used for recursive functions
function test() {
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
test(); // Outputs: 12345678910

View the other sections:

Note: This article is based on PHP version 7.1.